2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 // #define LOG_NDEBUG 0
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21 #include <sys/types.h>
26 #include <stdatomic.h>
30 #include <cutils/log.h>
31 #include <cutils/properties.h>
33 #include <binder/IPCThreadState.h>
34 #include <binder/IServiceManager.h>
35 #include <binder/MemoryHeapBase.h>
36 #include <binder/PermissionCache.h>
38 #include <ui/DisplayInfo.h>
39 #include <ui/DisplayStatInfo.h>
41 #include <gui/BitTube.h>
42 #include <gui/BufferQueue.h>
43 #include <gui/GuiConfig.h>
44 #include <gui/IDisplayEventConnection.h>
45 #include <gui/Surface.h>
46 #include <gui/GraphicBufferAlloc.h>
48 #include <ui/GraphicBufferAllocator.h>
49 #include <ui/PixelFormat.h>
50 #include <ui/UiConfig.h>
52 #include <utils/misc.h>
53 #include <utils/String8.h>
54 #include <utils/String16.h>
55 #include <utils/StopWatch.h>
56 #include <utils/Timers.h>
57 #include <utils/Trace.h>
59 #include <private/android_filesystem_config.h>
60 #include <private/gui/SyncFeatures.h>
64 #include "Colorizer.h"
65 #include "DdmConnection.h"
66 #include "DisplayDevice.h"
68 #include "EventControlThread.h"
69 #include "EventThread.h"
72 #include "SurfaceFlinger.h"
74 #include "DisplayHardware/FramebufferSurface.h"
75 #include "DisplayHardware/HWComposer.h"
76 #include "DisplayHardware/VirtualDisplaySurface.h"
78 #include "Effects/Daltonizer.h"
80 #include "RenderEngine/RenderEngine.h"
81 #include <cutils/compiler.h>
83 #define DISPLAY_COUNT 1
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
89 #define DEBUG_SCREENSHOTS false
91 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
95 // This is the phase offset in nanoseconds of the software vsync event
96 // relative to the vsync event reported by HWComposer. The software vsync
97 // event is when SurfaceFlinger and Choreographer-based applications run each
100 // This phase offset allows adjustment of the minimum latency from application
101 // wake-up (by Choregographer) time to the time at which the resulting window
102 // image is displayed. This value may be either positive (after the HW vsync)
103 // or negative (before the HW vsync). Setting it to 0 will result in a
104 // minimum latency of two vsync periods because the app and SurfaceFlinger
105 // will run just after the HW vsync. Setting it to a positive number will
106 // result in the minimum latency being:
108 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
110 // Note that reducing this latency makes it more likely for the applications
111 // to not have their window content image ready in time. When this happens
112 // the latency will end up being an additional vsync period, and animations
113 // will hiccup. Therefore, this latency should be tuned somewhat
114 // conservatively (or at least with awareness of the trade-off being made).
115 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
117 // This is the phase offset at which SurfaceFlinger's composition runs.
118 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
120 // ---------------------------------------------------------------------------
122 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
123 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
124 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
125 const String16 sDump("android.permission.DUMP");
127 // ---------------------------------------------------------------------------
129 SurfaceFlinger::SurfaceFlinger()
130 : BnSurfaceComposer(),
131 mTransactionFlags(0),
132 mTransactionPending(false),
133 mAnimTransactionPending(false),
134 mLayersRemoved(false),
135 mRepaintEverything(0),
137 mBootTime(systemTime()),
139 mVisibleRegionsDirty(false),
140 mGeometryInvalid(false),
141 mAnimCompositionPending(false),
145 mDebugDisableTransformHint(0),
146 mDebugInSwapBuffers(0),
147 mLastSwapBufferTime(0),
148 mDebugInTransaction(0),
149 mLastTransactionTime(0),
150 mBootFinished(false),
151 mForceFullDamage(false),
152 mPrimaryDispSync("PrimaryDispSync"),
153 mPrimaryHWVsyncEnabled(false),
154 mHWVsyncAvailable(false),
156 mHasColorMatrix(false),
157 mHasPoweredOff(false),
162 ALOGI("SurfaceFlinger is starting");
164 // debugging stuff...
165 char value[PROPERTY_VALUE_MAX];
167 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
168 mGpuToCpuSupported = !atoi(value);
170 property_get("debug.sf.drop_missed_frames", value, "0");
171 mDropMissedFrames = atoi(value);
173 property_get("debug.sf.showupdates", value, "0");
174 mDebugRegion = atoi(value);
176 property_get("debug.sf.ddms", value, "0");
177 mDebugDDMS = atoi(value);
179 if (!startDdmConnection()) {
180 // start failed, and DDMS debugging not enabled
184 ALOGI_IF(mDebugRegion, "showupdates enabled");
185 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
188 void SurfaceFlinger::onFirstRef()
190 mEventQueue.init(this);
193 SurfaceFlinger::~SurfaceFlinger()
195 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
196 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
197 eglTerminate(display);
200 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
202 // the window manager died on us. prepare its eulogy.
204 // restore initial conditions (default device unblank, etc)
205 initializeDisplays();
207 // restart the boot-animation
211 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
213 sp<ISurfaceComposerClient> bclient;
214 sp<Client> client(new Client(this));
215 status_t err = client->initCheck();
216 if (err == NO_ERROR) {
222 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
225 class DisplayToken : public BBinder {
226 sp<SurfaceFlinger> flinger;
227 virtual ~DisplayToken() {
228 // no more references, this display must be terminated
229 Mutex::Autolock _l(flinger->mStateLock);
230 flinger->mCurrentState.displays.removeItem(this);
231 flinger->setTransactionFlags(eDisplayTransactionNeeded);
234 DisplayToken(const sp<SurfaceFlinger>& flinger)
239 sp<BBinder> token = new DisplayToken(this);
241 Mutex::Autolock _l(mStateLock);
242 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
243 info.displayName = displayName;
244 mCurrentState.displays.add(token, info);
249 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
250 Mutex::Autolock _l(mStateLock);
252 ssize_t idx = mCurrentState.displays.indexOfKey(display);
254 ALOGW("destroyDisplay: invalid display token");
258 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
259 if (!info.isVirtualDisplay()) {
260 ALOGE("destroyDisplay called for non-virtual display");
264 mCurrentState.displays.removeItemsAt(idx);
265 setTransactionFlags(eDisplayTransactionNeeded);
268 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
269 ALOGV("createBuiltinDisplayLocked(%d)", type);
270 ALOGW_IF(mBuiltinDisplays[type],
271 "Overwriting display token for display type %d", type);
272 mBuiltinDisplays[type] = new BBinder();
273 // All non-virtual displays are currently considered secure.
274 DisplayDeviceState info(type, true);
275 mCurrentState.displays.add(mBuiltinDisplays[type], info);
278 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
279 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
280 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
283 return mBuiltinDisplays[id];
286 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
288 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
292 void SurfaceFlinger::bootFinished()
294 const nsecs_t now = systemTime();
295 const nsecs_t duration = now - mBootTime;
296 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
297 mBootFinished = true;
299 // wait patiently for the window manager death
300 const String16 name("window");
301 sp<IBinder> window(defaultServiceManager()->getService(name));
303 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
306 // stop boot animation
307 // formerly we would just kill the process, but we now ask it to exit so it
308 // can choose where to stop the animation.
309 property_set("service.bootanim.exit", "1");
311 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
312 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
313 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
316 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
317 class MessageDestroyGLTexture : public MessageBase {
318 RenderEngine& engine;
321 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
322 : engine(engine), texture(texture) {
324 virtual bool handler() {
325 engine.deleteTextures(1, &texture);
329 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
332 class DispSyncSource : public VSyncSource, private DispSync::Callback {
334 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
338 mTraceVsync(traceVsync),
339 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
340 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
345 mPhaseOffset(phaseOffset),
348 virtual ~DispSyncSource() {}
350 virtual void setVSyncEnabled(bool enable) {
351 Mutex::Autolock lock(mVsyncMutex);
353 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
354 static_cast<DispSync::Callback*>(this));
355 if (err != NO_ERROR) {
356 ALOGE("error registering vsync callback: %s (%d)",
357 strerror(-err), err);
359 //ATRACE_INT(mVsyncOnLabel.string(), 1);
361 status_t err = mDispSync->removeEventListener(
362 static_cast<DispSync::Callback*>(this));
363 if (err != NO_ERROR) {
364 ALOGE("error unregistering vsync callback: %s (%d)",
365 strerror(-err), err);
367 //ATRACE_INT(mVsyncOnLabel.string(), 0);
372 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
373 Mutex::Autolock lock(mCallbackMutex);
374 mCallback = callback;
377 virtual void setPhaseOffset(nsecs_t phaseOffset) {
378 Mutex::Autolock lock(mVsyncMutex);
380 // Normalize phaseOffset to [0, period)
381 auto period = mDispSync->getPeriod();
382 phaseOffset %= period;
383 if (phaseOffset < 0) {
384 // If we're here, then phaseOffset is in (-period, 0). After this
385 // operation, it will be in (0, period)
386 phaseOffset += period;
388 mPhaseOffset = phaseOffset;
390 // If we're not enabled, we don't need to mess with the listeners
395 // Remove the listener with the old offset
396 status_t err = mDispSync->removeEventListener(
397 static_cast<DispSync::Callback*>(this));
398 if (err != NO_ERROR) {
399 ALOGE("error unregistering vsync callback: %s (%d)",
400 strerror(-err), err);
403 // Add a listener with the new offset
404 err = mDispSync->addEventListener(mName, mPhaseOffset,
405 static_cast<DispSync::Callback*>(this));
406 if (err != NO_ERROR) {
407 ALOGE("error registering vsync callback: %s (%d)",
408 strerror(-err), err);
413 virtual void onDispSyncEvent(nsecs_t when) {
414 sp<VSyncSource::Callback> callback;
416 Mutex::Autolock lock(mCallbackMutex);
417 callback = mCallback;
420 mValue = (mValue + 1) % 2;
421 ATRACE_INT(mVsyncEventLabel.string(), mValue);
425 if (callback != NULL) {
426 callback->onVSyncEvent(when);
430 const char* const mName;
434 const bool mTraceVsync;
435 const String8 mVsyncOnLabel;
436 const String8 mVsyncEventLabel;
440 Mutex mCallbackMutex; // Protects the following
441 sp<VSyncSource::Callback> mCallback;
443 Mutex mVsyncMutex; // Protects the following
444 nsecs_t mPhaseOffset;
448 void SurfaceFlinger::init() {
449 ALOGI( "SurfaceFlinger's main thread ready to run. "
450 "Initializing graphics H/W...");
453 Mutex::Autolock _l(mStateLock);
455 // initialize EGL for the default display
456 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
457 eglInitialize(mEGLDisplay, NULL, NULL);
459 // start the EventThread
460 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
461 vsyncPhaseOffsetNs, true, "app");
462 mEventThread = new EventThread(vsyncSrc, *this);
463 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
464 sfVsyncPhaseOffsetNs, true, "sf");
465 mSFEventThread = new EventThread(sfVsyncSrc, *this);
466 mEventQueue.setEventThread(mSFEventThread);
468 // Get a RenderEngine for the given display / config (can't fail)
469 mRenderEngine = RenderEngine::create(mEGLDisplay,
470 HAL_PIXEL_FORMAT_RGBA_8888);
473 // Drop the state lock while we initialize the hardware composer. We drop
474 // the lock because on creation, it will call back into SurfaceFlinger to
475 // initialize the primary display.
476 mHwc = new HWComposer(this);
477 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
479 Mutex::Autolock _l(mStateLock);
481 // retrieve the EGL context that was selected/created
482 mEGLContext = mRenderEngine->getEGLContext();
484 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
485 "couldn't create EGLContext");
487 // make the GLContext current so that we can create textures when creating
488 // Layers (which may happens before we render something)
489 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
491 mEventControlThread = new EventControlThread(this);
492 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
494 // initialize our drawing state
495 mDrawingState = mCurrentState;
497 // set initial conditions (e.g. unblank default device)
498 initializeDisplays();
500 // start boot animation
503 ALOGV("Done initializing");
506 void SurfaceFlinger::startBootAnim() {
507 // start boot animation
508 property_set("service.bootanim.exit", "0");
509 property_set("ctl.start", "bootanim");
512 size_t SurfaceFlinger::getMaxTextureSize() const {
513 return mRenderEngine->getMaxTextureSize();
516 size_t SurfaceFlinger::getMaxViewportDims() const {
517 return mRenderEngine->getMaxViewportDims();
520 // ----------------------------------------------------------------------------
522 bool SurfaceFlinger::authenticateSurfaceTexture(
523 const sp<IGraphicBufferProducer>& bufferProducer) const {
524 Mutex::Autolock _l(mStateLock);
525 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
526 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
529 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
530 Vector<DisplayInfo>* configs) {
531 if ((configs == NULL) || (display.get() == NULL)) {
536 return NAME_NOT_FOUND;
538 int32_t type = NAME_NOT_FOUND;
539 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
540 if (display == mBuiltinDisplays[i]) {
550 // TODO: Not sure if display density should handled by SF any longer
552 static int getDensityFromProperty(char const* propName) {
553 char property[PROPERTY_VALUE_MAX];
555 if (property_get(propName, property, NULL) > 0) {
556 density = atoi(property);
561 static int getEmuDensity() {
562 return getDensityFromProperty("qemu.sf.lcd_density"); }
563 static int getBuildDensity() {
564 return getDensityFromProperty("ro.sf.lcd_density"); }
569 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
570 DisplayInfo info = DisplayInfo();
572 float xdpi = hwConfig->getDpiX();
573 float ydpi = hwConfig->getDpiY();
575 if (type == DisplayDevice::DISPLAY_PRIMARY) {
576 // The density of the device is provided by a build property
577 float density = Density::getBuildDensity() / 160.0f;
579 // the build doesn't provide a density -- this is wrong!
581 ALOGE("ro.sf.lcd_density must be defined as a build property");
582 density = xdpi / 160.0f;
584 if (Density::getEmuDensity()) {
585 // if "qemu.sf.lcd_density" is specified, it overrides everything
586 xdpi = ydpi = density = Density::getEmuDensity();
589 info.density = density;
591 // TODO: this needs to go away (currently needed only by webkit)
592 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
593 info.orientation = hw->getOrientation();
595 // TODO: where should this value come from?
596 static const int TV_DENSITY = 213;
597 info.density = TV_DENSITY / 160.0f;
598 info.orientation = 0;
601 info.w = hwConfig->getWidth();
602 info.h = hwConfig->getHeight();
605 info.fps = 1e9 / hwConfig->getVsyncPeriod();
606 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
608 // TODO: Hook this back up
609 info.colorTransform = 0;
611 // This is how far in advance a buffer must be queued for
612 // presentation at a given time. If you want a buffer to appear
613 // on the screen at time N, you must submit the buffer before
614 // (N - presentationDeadline).
616 // Normally it's one full refresh period (to give SF a chance to
617 // latch the buffer), but this can be reduced by configuring a
618 // DispSync offset. Any additional delays introduced by the hardware
619 // composer or panel must be accounted for here.
621 // We add an additional 1ms to allow for processing time and
622 // differences between the ideal and actual refresh rate.
623 info.presentationDeadline = hwConfig->getVsyncPeriod() -
624 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
626 // All non-virtual displays are currently considered secure.
629 configs->push_back(info);
635 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
636 DisplayStatInfo* stats) {
641 // FIXME for now we always return stats for the primary display
642 memset(stats, 0, sizeof(*stats));
643 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
644 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
648 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
649 sp<DisplayDevice> device(getDisplayDevice(display));
650 if (device != NULL) {
651 return device->getActiveConfig();
656 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
657 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
659 int32_t type = hw->getDisplayType();
660 int currentMode = hw->getActiveConfig();
662 if (mode == currentMode) {
663 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
667 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
668 ALOGW("Trying to set config for virtual display");
672 hw->setActiveConfig(mode);
673 getHwComposer().setActiveConfig(type, mode);
676 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
677 class MessageSetActiveConfig: public MessageBase {
678 SurfaceFlinger& mFlinger;
679 sp<IBinder> mDisplay;
682 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
684 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
685 virtual bool handler() {
686 Vector<DisplayInfo> configs;
687 mFlinger.getDisplayConfigs(mDisplay, &configs);
688 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
689 ALOGE("Attempt to set active config = %d for display with %zu configs",
690 mMode, configs.size());
692 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
694 ALOGE("Attempt to set active config = %d for null display %p",
695 mMode, mDisplay.get());
696 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
697 ALOGW("Attempt to set active config = %d for virtual display",
700 mFlinger.setActiveConfigInternal(hw, mMode);
705 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
706 postMessageSync(msg);
710 status_t SurfaceFlinger::clearAnimationFrameStats() {
711 Mutex::Autolock _l(mStateLock);
712 mAnimFrameTracker.clearStats();
716 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
717 Mutex::Autolock _l(mStateLock);
718 mAnimFrameTracker.getStats(outStats);
722 status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
723 HdrCapabilities* outCapabilities) const {
724 Mutex::Autolock _l(mStateLock);
726 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
727 if (displayDevice == nullptr) {
728 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
732 std::unique_ptr<HdrCapabilities> capabilities =
733 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
735 std::swap(*outCapabilities, *capabilities);
743 // ----------------------------------------------------------------------------
745 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
746 return mEventThread->createEventConnection();
749 // ----------------------------------------------------------------------------
751 void SurfaceFlinger::waitForEvent() {
752 mEventQueue.waitMessage();
755 void SurfaceFlinger::signalTransaction() {
756 mEventQueue.invalidate();
759 void SurfaceFlinger::signalLayerUpdate() {
760 mEventQueue.invalidate();
763 void SurfaceFlinger::signalRefresh() {
764 mEventQueue.refresh();
767 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
768 nsecs_t reltime, uint32_t /* flags */) {
769 return mEventQueue.postMessage(msg, reltime);
772 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
773 nsecs_t reltime, uint32_t /* flags */) {
774 status_t res = mEventQueue.postMessage(msg, reltime);
775 if (res == NO_ERROR) {
781 void SurfaceFlinger::run() {
787 void SurfaceFlinger::enableHardwareVsync() {
788 Mutex::Autolock _l(mHWVsyncLock);
789 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
790 mPrimaryDispSync.beginResync();
791 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
792 mEventControlThread->setVsyncEnabled(true);
793 mPrimaryHWVsyncEnabled = true;
797 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
798 Mutex::Autolock _l(mHWVsyncLock);
801 mHWVsyncAvailable = true;
802 } else if (!mHWVsyncAvailable) {
803 // Hardware vsync is not currently available, so abort the resync
808 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
809 const nsecs_t period = activeConfig->getVsyncPeriod();
811 mPrimaryDispSync.reset();
812 mPrimaryDispSync.setPeriod(period);
814 if (!mPrimaryHWVsyncEnabled) {
815 mPrimaryDispSync.beginResync();
816 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
817 mEventControlThread->setVsyncEnabled(true);
818 mPrimaryHWVsyncEnabled = true;
822 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
823 Mutex::Autolock _l(mHWVsyncLock);
824 if (mPrimaryHWVsyncEnabled) {
825 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
826 mEventControlThread->setVsyncEnabled(false);
827 mPrimaryDispSync.endResync();
828 mPrimaryHWVsyncEnabled = false;
830 if (makeUnavailable) {
831 mHWVsyncAvailable = false;
835 void SurfaceFlinger::resyncWithRateLimit() {
836 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
837 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
838 resyncToHardwareVsync(false);
842 void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
843 bool needsHwVsync = false;
845 { // Scope for the lock
846 Mutex::Autolock _l(mHWVsyncLock);
847 if (type == 0 && mPrimaryHWVsyncEnabled) {
848 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
853 enableHardwareVsync();
855 disableHardwareVsync(false);
859 void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
860 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
861 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
862 Mutex::Autolock lock(mStateLock);
864 // All non-virtual displays are currently considered secure.
865 bool isSecure = true;
867 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
868 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
869 wp<IBinder> token = mBuiltinDisplays[type];
871 sp<IGraphicBufferProducer> producer;
872 sp<IGraphicBufferConsumer> consumer;
873 BufferQueue::createBufferQueue(&producer, &consumer,
874 new GraphicBufferAlloc());
876 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
877 DisplayDevice::DISPLAY_PRIMARY, consumer);
878 sp<DisplayDevice> hw = new DisplayDevice(this,
879 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
880 producer, mRenderEngine->getEGLConfig());
881 mDisplays.add(token, hw);
883 auto type = DisplayDevice::DISPLAY_EXTERNAL;
884 Mutex::Autolock _l(mStateLock);
886 createBuiltinDisplayLocked(type);
888 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
889 mBuiltinDisplays[type].clear();
891 setTransactionFlags(eDisplayTransactionNeeded);
893 // Defer EventThread notification until SF has updated mDisplays.
897 void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
899 getHwComposer().setVsyncEnabled(disp,
900 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
903 void SurfaceFlinger::onMessageReceived(int32_t what) {
906 case MessageQueue::TRANSACTION: {
907 handleMessageTransaction();
910 case MessageQueue::INVALIDATE: {
911 bool refreshNeeded = handleMessageTransaction();
912 refreshNeeded |= handleMessageInvalidate();
913 refreshNeeded |= mRepaintEverything;
915 // Signal a refresh if a transaction modified the window state,
916 // a new buffer was latched, or if HWC has requested a full
922 case MessageQueue::REFRESH: {
923 handleMessageRefresh();
929 bool SurfaceFlinger::handleMessageTransaction() {
930 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
931 if (transactionFlags) {
932 handleTransaction(transactionFlags);
938 bool SurfaceFlinger::handleMessageInvalidate() {
940 return handlePageFlip();
943 void SurfaceFlinger::handleMessageRefresh() {
946 #ifdef ENABLE_FENCE_TRACKING
947 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
949 nsecs_t refreshStartTime = 0;
951 static nsecs_t previousExpectedPresent = 0;
952 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
953 static bool previousFrameMissed = false;
954 bool frameMissed = (expectedPresent == previousExpectedPresent);
955 if (frameMissed != previousFrameMissed) {
956 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
958 previousFrameMissed = frameMissed;
960 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
961 // Latch buffers, but don't send anything to HWC, then signal another
962 // wakeup for the next vsync
967 rebuildLayerStacks();
969 doDebugFlashRegions();
971 postComposition(refreshStartTime);
974 // Release any buffers which were replaced this frame
975 for (auto& layer : mLayersWithQueuedFrames) {
976 layer->releasePendingBuffer();
978 mLayersWithQueuedFrames.clear();
980 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
983 void SurfaceFlinger::doDebugFlashRegions()
985 // is debugging enabled
986 if (CC_LIKELY(!mDebugRegion))
989 const bool repaintEverything = mRepaintEverything;
990 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
991 const sp<DisplayDevice>& hw(mDisplays[dpy]);
992 if (hw->isDisplayOn()) {
993 // transform the dirty region into this screen's coordinate space
994 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
995 if (!dirtyRegion.isEmpty()) {
996 // redraw the whole screen
997 doComposeSurfaces(hw, Region(hw->bounds()));
999 // and draw the dirty region
1000 const int32_t height = hw->getHeight();
1001 RenderEngine& engine(getRenderEngine());
1002 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1004 hw->swapBuffers(getHwComposer());
1011 if (mDebugRegion > 1) {
1012 usleep(mDebugRegion * 1000);
1015 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1016 status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
1017 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1018 " %d (%s)", displayId, result, strerror(-result));
1022 void SurfaceFlinger::preComposition()
1025 ALOGV("preComposition");
1027 bool needExtraInvalidate = false;
1028 const LayerVector& layers(mDrawingState.layersSortedByZ);
1029 const size_t count = layers.size();
1030 for (size_t i=0 ; i<count ; i++) {
1031 if (layers[i]->onPreComposition()) {
1032 needExtraInvalidate = true;
1035 if (needExtraInvalidate) {
1036 signalLayerUpdate();
1040 #ifdef ENABLE_FENCE_TRACKING
1041 void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
1043 void SurfaceFlinger::postComposition(nsecs_t /*refreshStartTime*/)
1047 ALOGV("postComposition");
1049 const LayerVector& layers(mDrawingState.layersSortedByZ);
1050 const size_t count = layers.size();
1051 for (size_t i=0 ; i<count ; i++) {
1052 layers[i]->onPostComposition();
1055 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
1057 if (presentFence->isValid()) {
1058 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1059 enableHardwareVsync();
1061 disableHardwareVsync(false);
1065 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1066 if (kIgnorePresentFences) {
1067 if (hw->isDisplayOn()) {
1068 enableHardwareVsync();
1072 #ifdef ENABLE_FENCE_TRACKING
1073 mFenceTracker.addFrame(refreshStartTime, presentFence,
1074 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1077 if (mAnimCompositionPending) {
1078 mAnimCompositionPending = false;
1080 if (presentFence->isValid()) {
1081 mAnimFrameTracker.setActualPresentFence(presentFence);
1083 // The HWC doesn't support present fences, so use the refresh
1084 // timestamp instead.
1085 nsecs_t presentTime =
1086 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1087 mAnimFrameTracker.setActualPresentTime(presentTime);
1089 mAnimFrameTracker.advanceFrame();
1092 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1096 nsecs_t currentTime = systemTime();
1097 if (mHasPoweredOff) {
1098 mHasPoweredOff = false;
1100 nsecs_t period = mPrimaryDispSync.getPeriod();
1101 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1102 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1103 if (numPeriods < NUM_BUCKETS - 1) {
1104 mFrameBuckets[numPeriods] += elapsedTime;
1106 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1108 mTotalTime += elapsedTime;
1110 mLastSwapTime = currentTime;
1113 void SurfaceFlinger::rebuildLayerStacks() {
1115 ALOGV("rebuildLayerStacks");
1117 // rebuild the visible layer list per screen
1118 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1120 mVisibleRegionsDirty = false;
1121 invalidateHwcGeometry();
1123 const LayerVector& layers(mDrawingState.layersSortedByZ);
1124 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1125 Region opaqueRegion;
1127 Vector<sp<Layer>> layersSortedByZ;
1128 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1129 const Transform& tr(displayDevice->getTransform());
1130 const Rect bounds(displayDevice->getBounds());
1131 if (displayDevice->isDisplayOn()) {
1132 SurfaceFlinger::computeVisibleRegions(layers,
1133 displayDevice->getLayerStack(), dirtyRegion,
1136 const size_t count = layers.size();
1137 for (size_t i=0 ; i<count ; i++) {
1138 const sp<Layer>& layer(layers[i]);
1139 const Layer::State& s(layer->getDrawingState());
1140 if (s.layerStack == displayDevice->getLayerStack()) {
1141 Region drawRegion(tr.transform(
1142 layer->visibleNonTransparentRegion));
1143 drawRegion.andSelf(bounds);
1144 if (!drawRegion.isEmpty()) {
1145 layersSortedByZ.add(layer);
1147 // Clear out the HWC layer if this layer was
1148 // previously visible, but no longer is
1149 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1155 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1156 displayDevice->undefinedRegion.set(bounds);
1157 displayDevice->undefinedRegion.subtractSelf(
1158 tr.transform(opaqueRegion));
1159 displayDevice->dirtyRegion.orSelf(dirtyRegion);
1164 void SurfaceFlinger::setUpHWComposer() {
1166 ALOGV("setUpHWComposer");
1168 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1169 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1170 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1171 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1173 // If nothing has changed (!dirty), don't recompose.
1174 // If something changed, but we don't currently have any visible layers,
1175 // and didn't when we last did a composition, then skip it this time.
1176 // The second rule does two things:
1177 // - When all layers are removed from a display, we'll emit one black
1178 // frame, then nothing more until we get new layers.
1179 // - When a display is created with a private layer stack, we won't
1180 // emit any black frames until a layer is added to the layer stack.
1181 bool mustRecompose = dirty && !(empty && wasEmpty);
1183 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1184 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1185 mustRecompose ? "doing" : "skipping",
1188 wasEmpty ? "+" : "-");
1190 mDisplays[dpy]->beginFrame(mustRecompose);
1192 if (mustRecompose) {
1193 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1197 // build the h/w work list
1198 if (CC_UNLIKELY(mGeometryInvalid)) {
1199 mGeometryInvalid = false;
1200 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1201 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1202 const auto hwcId = displayDevice->getHwcDisplayId();
1204 const Vector<sp<Layer>>& currentLayers(
1205 displayDevice->getVisibleLayersSortedByZ());
1206 bool foundLayerWithoutHwc = false;
1207 for (auto& layer : currentLayers) {
1208 if (!layer->hasHwcLayer(hwcId)) {
1209 auto hwcLayer = mHwc->createLayer(hwcId);
1211 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1213 layer->forceClientComposition(hwcId);
1214 foundLayerWithoutHwc = true;
1219 layer->setGeometry(displayDevice);
1220 if (mDebugDisableHWC || mDebugRegion || mDaltonize ||
1222 layer->forceClientComposition(hwcId);
1229 // Set the per-frame data
1230 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1231 auto& displayDevice = mDisplays[displayId];
1232 const auto hwcId = displayDevice->getHwcDisplayId();
1236 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1237 layer->setPerFrameData(displayDevice);
1241 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1242 status_t result = mDisplays[displayId]->prepareFrame(*mHwc);
1243 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1244 " %d (%s)", displayId, result, strerror(-result));
1248 void SurfaceFlinger::doComposition() {
1250 ALOGV("doComposition");
1252 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1253 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1254 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1255 if (hw->isDisplayOn()) {
1256 // transform the dirty region into this screen's coordinate space
1257 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1259 // repaint the framebuffer (if needed)
1260 doDisplayComposition(hw, dirtyRegion);
1262 hw->dirtyRegion.clear();
1263 hw->flip(hw->swapRegion);
1264 hw->swapRegion.clear();
1270 void SurfaceFlinger::postFramebuffer()
1273 ALOGV("postFramebuffer");
1275 const nsecs_t now = systemTime();
1276 mDebugInSwapBuffers = now;
1278 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1279 auto& displayDevice = mDisplays[displayId];
1280 const auto hwcId = displayDevice->getHwcDisplayId();
1282 mHwc->commit(hwcId);
1284 displayDevice->onSwapBuffersCompleted();
1285 if (displayId == 0) {
1286 // Make the default display current because the VirtualDisplayDevice
1287 // code cannot deal with dequeueBuffer() being called outside of the
1288 // composition loop; however the code below can call glFlush() which
1289 // is allowed to (and does in some case) call dequeueBuffer().
1290 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1292 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1293 sp<Fence> releaseFence = Fence::NO_FENCE;
1294 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1295 releaseFence = displayDevice->getClientTargetAcquireFence();
1297 auto hwcLayer = layer->getHwcLayer(hwcId);
1298 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
1300 layer->onLayerDisplayed(releaseFence);
1303 mHwc->clearReleaseFences(hwcId);
1307 mLastSwapBufferTime = systemTime() - now;
1308 mDebugInSwapBuffers = 0;
1310 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1311 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1316 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1320 // here we keep a copy of the drawing state (that is the state that's
1321 // going to be overwritten by handleTransactionLocked()) outside of
1322 // mStateLock so that the side-effects of the State assignment
1323 // don't happen with mStateLock held (which can cause deadlocks).
1324 State drawingState(mDrawingState);
1326 Mutex::Autolock _l(mStateLock);
1327 const nsecs_t now = systemTime();
1328 mDebugInTransaction = now;
1330 // Here we're guaranteed that some transaction flags are set
1331 // so we can call handleTransactionLocked() unconditionally.
1332 // We call getTransactionFlags(), which will also clear the flags,
1333 // with mStateLock held to guarantee that mCurrentState won't change
1334 // until the transaction is committed.
1336 transactionFlags = getTransactionFlags(eTransactionMask);
1337 handleTransactionLocked(transactionFlags);
1339 mLastTransactionTime = systemTime() - now;
1340 mDebugInTransaction = 0;
1341 invalidateHwcGeometry();
1342 // here the transaction has been committed
1345 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1347 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1348 const size_t count = currentLayers.size();
1350 // Notify all layers of available frames
1351 for (size_t i = 0; i < count; ++i) {
1352 currentLayers[i]->notifyAvailableFrames();
1356 * Traversal of the children
1357 * (perform the transaction for each of them if needed)
1360 if (transactionFlags & eTraversalNeeded) {
1361 for (size_t i=0 ; i<count ; i++) {
1362 const sp<Layer>& layer(currentLayers[i]);
1363 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1364 if (!trFlags) continue;
1366 const uint32_t flags = layer->doTransaction(0);
1367 if (flags & Layer::eVisibleRegion)
1368 mVisibleRegionsDirty = true;
1373 * Perform display own transactions if needed
1376 if (transactionFlags & eDisplayTransactionNeeded) {
1377 // here we take advantage of Vector's copy-on-write semantics to
1378 // improve performance by skipping the transaction entirely when
1379 // know that the lists are identical
1380 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1381 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1382 if (!curr.isIdenticalTo(draw)) {
1383 mVisibleRegionsDirty = true;
1384 const size_t cc = curr.size();
1385 size_t dc = draw.size();
1387 // find the displays that were removed
1388 // (ie: in drawing state but not in current state)
1389 // also handle displays that changed
1390 // (ie: displays that are in both lists)
1391 for (size_t i=0 ; i<dc ; i++) {
1392 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1394 // in drawing state but not in current state
1395 if (!draw[i].isMainDisplay()) {
1396 // Call makeCurrent() on the primary display so we can
1397 // be sure that nothing associated with this display
1399 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1400 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1401 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1403 hw->disconnect(getHwComposer());
1404 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1405 mEventThread->onHotplugReceived(draw[i].type, false);
1406 mDisplays.removeItem(draw.keyAt(i));
1408 ALOGW("trying to remove the main display");
1411 // this display is in both lists. see if something changed.
1412 const DisplayDeviceState& state(curr[j]);
1413 const wp<IBinder>& display(curr.keyAt(j));
1414 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1415 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1416 if (state_binder != draw_binder) {
1417 // changing the surface is like destroying and
1418 // recreating the DisplayDevice, so we just remove it
1419 // from the drawing state, so that it get re-added
1421 sp<DisplayDevice> hw(getDisplayDevice(display));
1423 hw->disconnect(getHwComposer());
1424 mDisplays.removeItem(display);
1425 mDrawingState.displays.removeItemsAt(i);
1427 // at this point we must loop to the next item
1431 const sp<DisplayDevice> disp(getDisplayDevice(display));
1433 if (state.layerStack != draw[i].layerStack) {
1434 disp->setLayerStack(state.layerStack);
1436 if ((state.orientation != draw[i].orientation)
1437 || (state.viewport != draw[i].viewport)
1438 || (state.frame != draw[i].frame))
1440 disp->setProjection(state.orientation,
1441 state.viewport, state.frame);
1443 if (state.width != draw[i].width || state.height != draw[i].height) {
1444 disp->setDisplaySize(state.width, state.height);
1450 // find displays that were added
1451 // (ie: in current state but not in drawing state)
1452 for (size_t i=0 ; i<cc ; i++) {
1453 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1454 const DisplayDeviceState& state(curr[i]);
1456 sp<DisplaySurface> dispSurface;
1457 sp<IGraphicBufferProducer> producer;
1458 sp<IGraphicBufferProducer> bqProducer;
1459 sp<IGraphicBufferConsumer> bqConsumer;
1460 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1461 new GraphicBufferAlloc());
1464 if (state.isVirtualDisplay()) {
1465 // Virtual displays without a surface are dormant:
1466 // they have external state (layer stack, projection,
1467 // etc.) but no internal state (i.e. a DisplayDevice).
1468 if (state.surface != NULL) {
1471 int status = state.surface->query(
1472 NATIVE_WINDOW_WIDTH, &width);
1473 ALOGE_IF(status != NO_ERROR,
1474 "Unable to query width (%d)", status);
1476 status = state.surface->query(
1477 NATIVE_WINDOW_HEIGHT, &height);
1478 ALOGE_IF(status != NO_ERROR,
1479 "Unable to query height (%d)", status);
1481 mHwc->allocateVirtualDisplay(width, height,
1484 sp<VirtualDisplaySurface> vds =
1485 new VirtualDisplaySurface(*mHwc,
1486 hwcId, state.surface, bqProducer,
1487 bqConsumer, state.displayName);
1493 ALOGE_IF(state.surface!=NULL,
1494 "adding a supported display, but rendering "
1495 "surface is provided (%p), ignoring it",
1496 state.surface.get());
1497 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1498 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1499 dispSurface = new FramebufferSurface(*mHwc,
1500 DisplayDevice::DISPLAY_EXTERNAL,
1502 producer = bqProducer;
1504 ALOGE("Attempted to add non-external non-virtual"
1509 const wp<IBinder>& display(curr.keyAt(i));
1510 if (dispSurface != NULL) {
1511 sp<DisplayDevice> hw = new DisplayDevice(this,
1512 state.type, hwcId, state.isSecure, display,
1513 dispSurface, producer,
1514 mRenderEngine->getEGLConfig());
1515 hw->setLayerStack(state.layerStack);
1516 hw->setProjection(state.orientation,
1517 state.viewport, state.frame);
1518 hw->setDisplayName(state.displayName);
1519 mDisplays.add(display, hw);
1520 if (!state.isVirtualDisplay()) {
1521 mEventThread->onHotplugReceived(state.type, true);
1529 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1530 // The transform hint might have changed for some layers
1531 // (either because a display has changed, or because a layer
1534 // Walk through all the layers in currentLayers,
1535 // and update their transform hint.
1537 // If a layer is visible only on a single display, then that
1538 // display is used to calculate the hint, otherwise we use the
1541 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1542 // the hint is set before we acquire a buffer from the surface texture.
1544 // NOTE: layer transactions have taken place already, so we use their
1545 // drawing state. However, SurfaceFlinger's own transaction has not
1546 // happened yet, so we must use the current state layer list
1547 // (soon to become the drawing state list).
1549 sp<const DisplayDevice> disp;
1550 uint32_t currentlayerStack = 0;
1551 for (size_t i=0; i<count; i++) {
1552 // NOTE: we rely on the fact that layers are sorted by
1553 // layerStack first (so we don't have to traverse the list
1554 // of displays for every layer).
1555 const sp<Layer>& layer(currentLayers[i]);
1556 uint32_t layerStack = layer->getDrawingState().layerStack;
1557 if (i==0 || currentlayerStack != layerStack) {
1558 currentlayerStack = layerStack;
1559 // figure out if this layerstack is mirrored
1560 // (more than one display) if so, pick the default display,
1561 // if not, pick the only display it's on.
1563 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1564 sp<const DisplayDevice> hw(mDisplays[dpy]);
1565 if (hw->getLayerStack() == currentlayerStack) {
1576 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1577 // redraw after transform hint changes. See bug 8508397.
1579 // could be null when this layer is using a layerStack
1580 // that is not visible on any display. Also can occur at
1581 // screen off/on times.
1582 disp = getDefaultDisplayDevice();
1584 layer->updateTransformHint(disp);
1590 * Perform our own transaction if needed
1593 const LayerVector& layers(mDrawingState.layersSortedByZ);
1594 if (currentLayers.size() > layers.size()) {
1595 // layers have been added
1596 mVisibleRegionsDirty = true;
1599 // some layers might have been removed, so
1600 // we need to update the regions they're exposing.
1601 if (mLayersRemoved) {
1602 mLayersRemoved = false;
1603 mVisibleRegionsDirty = true;
1604 const size_t count = layers.size();
1605 for (size_t i=0 ; i<count ; i++) {
1606 const sp<Layer>& layer(layers[i]);
1607 if (currentLayers.indexOf(layer) < 0) {
1608 // this layer is not visible anymore
1609 // TODO: we could traverse the tree from front to back and
1610 // compute the actual visible region
1611 // TODO: we could cache the transformed region
1612 const Layer::State& s(layer->getDrawingState());
1613 Region visibleReg = s.active.transform.transform(
1614 Region(Rect(s.active.w, s.active.h)));
1615 invalidateLayerStack(s.layerStack, visibleReg);
1620 commitTransaction();
1622 updateCursorAsync();
1625 void SurfaceFlinger::updateCursorAsync()
1627 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1628 auto& displayDevice = mDisplays[displayId];
1629 if (displayDevice->getHwcDisplayId() < 0) {
1633 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1634 layer->updateCursorPosition(displayDevice);
1639 void SurfaceFlinger::commitTransaction()
1641 if (!mLayersPendingRemoval.isEmpty()) {
1642 // Notify removed layers now that they can't be drawn from
1643 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1644 mLayersPendingRemoval[i]->onRemoved();
1646 mLayersPendingRemoval.clear();
1649 // If this transaction is part of a window animation then the next frame
1650 // we composite should be considered an animation as well.
1651 mAnimCompositionPending = mAnimTransactionPending;
1653 mDrawingState = mCurrentState;
1654 mTransactionPending = false;
1655 mAnimTransactionPending = false;
1656 mTransactionCV.broadcast();
1659 void SurfaceFlinger::computeVisibleRegions(
1660 const LayerVector& currentLayers, uint32_t layerStack,
1661 Region& outDirtyRegion, Region& outOpaqueRegion)
1664 ALOGV("computeVisibleRegions");
1666 Region aboveOpaqueLayers;
1667 Region aboveCoveredLayers;
1670 outDirtyRegion.clear();
1672 size_t i = currentLayers.size();
1674 const sp<Layer>& layer = currentLayers[i];
1676 // start with the whole surface at its current location
1677 const Layer::State& s(layer->getDrawingState());
1679 // only consider the layers on the given layer stack
1680 if (s.layerStack != layerStack)
1684 * opaqueRegion: area of a surface that is fully opaque.
1686 Region opaqueRegion;
1689 * visibleRegion: area of a surface that is visible on screen
1690 * and not fully transparent. This is essentially the layer's
1691 * footprint minus the opaque regions above it.
1692 * Areas covered by a translucent surface are considered visible.
1694 Region visibleRegion;
1697 * coveredRegion: area of a surface that is covered by all
1698 * visible regions above it (which includes the translucent areas).
1700 Region coveredRegion;
1703 * transparentRegion: area of a surface that is hinted to be completely
1704 * transparent. This is only used to tell when the layer has no visible
1705 * non-transparent regions and can be removed from the layer list. It
1706 * does not affect the visibleRegion of this layer or any layers
1707 * beneath it. The hint may not be correct if apps don't respect the
1708 * SurfaceView restrictions (which, sadly, some don't).
1710 Region transparentRegion;
1713 // handle hidden surfaces by setting the visible region to empty
1714 if (CC_LIKELY(layer->isVisible())) {
1715 const bool translucent = !layer->isOpaque(s);
1716 Rect bounds(s.active.transform.transform(layer->computeBounds()));
1717 visibleRegion.set(bounds);
1718 if (!visibleRegion.isEmpty()) {
1719 // Remove the transparent area from the visible region
1721 const Transform tr(s.active.transform);
1722 if (tr.transformed()) {
1723 if (tr.preserveRects()) {
1724 // transform the transparent region
1725 transparentRegion = tr.transform(s.activeTransparentRegion);
1727 // transformation too complex, can't do the
1728 // transparent region optimization.
1729 transparentRegion.clear();
1732 transparentRegion = s.activeTransparentRegion;
1736 // compute the opaque region
1737 const int32_t layerOrientation = s.active.transform.getOrientation();
1738 if (s.alpha == 1.0f && !translucent &&
1739 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1740 // the opaque region is the layer's footprint
1741 opaqueRegion = visibleRegion;
1746 // Clip the covered region to the visible region
1747 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1749 // Update aboveCoveredLayers for next (lower) layer
1750 aboveCoveredLayers.orSelf(visibleRegion);
1752 // subtract the opaque region covered by the layers above us
1753 visibleRegion.subtractSelf(aboveOpaqueLayers);
1755 // compute this layer's dirty region
1756 if (layer->contentDirty) {
1757 // we need to invalidate the whole region
1758 dirty = visibleRegion;
1759 // as well, as the old visible region
1760 dirty.orSelf(layer->visibleRegion);
1761 layer->contentDirty = false;
1763 /* compute the exposed region:
1764 * the exposed region consists of two components:
1765 * 1) what's VISIBLE now and was COVERED before
1766 * 2) what's EXPOSED now less what was EXPOSED before
1768 * note that (1) is conservative, we start with the whole
1769 * visible region but only keep what used to be covered by
1770 * something -- which mean it may have been exposed.
1772 * (2) handles areas that were not covered by anything but got
1773 * exposed because of a resize.
1775 const Region newExposed = visibleRegion - coveredRegion;
1776 const Region oldVisibleRegion = layer->visibleRegion;
1777 const Region oldCoveredRegion = layer->coveredRegion;
1778 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1779 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1781 dirty.subtractSelf(aboveOpaqueLayers);
1783 // accumulate to the screen dirty region
1784 outDirtyRegion.orSelf(dirty);
1786 // Update aboveOpaqueLayers for next (lower) layer
1787 aboveOpaqueLayers.orSelf(opaqueRegion);
1789 // Store the visible region in screen space
1790 layer->setVisibleRegion(visibleRegion);
1791 layer->setCoveredRegion(coveredRegion);
1792 layer->setVisibleNonTransparentRegion(
1793 visibleRegion.subtract(transparentRegion));
1796 outOpaqueRegion = aboveOpaqueLayers;
1799 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1800 const Region& dirty) {
1801 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1802 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1803 if (hw->getLayerStack() == layerStack) {
1804 hw->dirtyRegion.orSelf(dirty);
1809 bool SurfaceFlinger::handlePageFlip()
1811 ALOGV("handlePageFlip");
1815 bool visibleRegions = false;
1816 const LayerVector& layers(mDrawingState.layersSortedByZ);
1817 bool frameQueued = false;
1819 // Store the set of layers that need updates. This set must not change as
1820 // buffers are being latched, as this could result in a deadlock.
1821 // Example: Two producers share the same command stream and:
1822 // 1.) Layer 0 is latched
1823 // 2.) Layer 0 gets a new frame
1824 // 2.) Layer 1 gets a new frame
1825 // 3.) Layer 1 is latched.
1826 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1827 // second frame. But layer 0's second frame could be waiting on display.
1828 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1829 const sp<Layer>& layer(layers[i]);
1830 if (layer->hasQueuedFrame()) {
1832 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1833 mLayersWithQueuedFrames.push_back(layer.get());
1835 layer->useEmptyDamage();
1838 layer->useEmptyDamage();
1841 for (auto& layer : mLayersWithQueuedFrames) {
1842 const Region dirty(layer->latchBuffer(visibleRegions));
1843 layer->useSurfaceDamage();
1844 const Layer::State& s(layer->getDrawingState());
1845 invalidateLayerStack(s.layerStack, dirty);
1848 mVisibleRegionsDirty |= visibleRegions;
1850 // If we will need to wake up at some time in the future to deal with a
1851 // queued frame that shouldn't be displayed during this vsync period, wake
1852 // up during the next vsync period to check again.
1853 if (frameQueued && mLayersWithQueuedFrames.empty()) {
1854 signalLayerUpdate();
1857 // Only continue with the refresh if there is actually new work to do
1858 return !mLayersWithQueuedFrames.empty();
1861 void SurfaceFlinger::invalidateHwcGeometry()
1863 mGeometryInvalid = true;
1867 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1868 const Region& inDirtyRegion)
1870 // We only need to actually compose the display if:
1871 // 1) It is being handled by hardware composer, which may need this to
1872 // keep its virtual display state machine in sync, or
1873 // 2) There is work to be done (the dirty region isn't empty)
1874 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1875 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1876 ALOGV("Skipping display composition");
1880 ALOGV("doDisplayComposition");
1882 Region dirtyRegion(inDirtyRegion);
1884 // compute the invalid region
1885 hw->swapRegion.orSelf(dirtyRegion);
1887 uint32_t flags = hw->getFlags();
1888 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1889 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1890 // takes a rectangle, we must make sure to update that whole
1891 // rectangle in that case
1892 dirtyRegion.set(hw->swapRegion.bounds());
1894 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1895 // We need to redraw the rectangle that will be updated
1896 // (pushed to the framebuffer).
1897 // This is needed because PARTIAL_UPDATES only takes one
1898 // rectangle instead of a region (see DisplayDevice::flip())
1899 dirtyRegion.set(hw->swapRegion.bounds());
1901 // we need to redraw everything (the whole screen)
1902 dirtyRegion.set(hw->bounds());
1903 hw->swapRegion = dirtyRegion;
1907 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1908 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1910 RenderEngine& engine(getRenderEngine());
1911 mat4 colorMatrix = mColorMatrix;
1913 colorMatrix = colorMatrix * mDaltonizer();
1915 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1916 doComposeSurfaces(hw, dirtyRegion);
1917 engine.setupColorTransform(oldMatrix);
1920 // update the swap region and clear the dirty region
1921 hw->swapRegion.orSelf(dirtyRegion);
1923 // swap buffers (presentation)
1924 hw->swapBuffers(getHwComposer());
1927 bool SurfaceFlinger::doComposeSurfaces(
1928 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
1930 ALOGV("doComposeSurfaces");
1932 const auto hwcId = displayDevice->getHwcDisplayId();
1933 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1934 if (hasClientComposition) {
1935 ALOGV("hasClientComposition");
1937 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
1938 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1939 displayDevice->getDisplayName().string());
1940 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1941 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1942 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1947 // Never touch the framebuffer if we don't have any framebuffer layers
1948 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1949 if (hasDeviceComposition) {
1950 // when using overlays, we assume a fully transparent framebuffer
1951 // NOTE: we could reduce how much we need to clear, for instance
1952 // remove where there are opaque FB layers. however, on some
1953 // GPUs doing a "clean slate" clear might be more efficient.
1954 // We'll revisit later if needed.
1955 mRenderEngine->clearWithColor(0, 0, 0, 0);
1957 // we start with the whole screen area
1958 const Region bounds(displayDevice->getBounds());
1960 // we remove the scissor part
1961 // we're left with the letterbox region
1962 // (common case is that letterbox ends-up being empty)
1963 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
1965 // compute the area to clear
1966 Region region(displayDevice->undefinedRegion.merge(letterbox));
1968 // but limit it to the dirty region
1969 region.andSelf(dirty);
1971 // screen is already cleared here
1972 if (!region.isEmpty()) {
1973 // can happen with SurfaceView
1974 drawWormhole(displayDevice, region);
1978 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1979 // just to be on the safe side, we don't set the
1980 // scissor on the main display. It should never be needed
1981 // anyways (though in theory it could since the API allows it).
1982 const Rect& bounds(displayDevice->getBounds());
1983 const Rect& scissor(displayDevice->getScissor());
1984 if (scissor != bounds) {
1985 // scissor doesn't match the screen's dimensions, so we
1986 // need to clear everything outside of it and enable
1987 // the GL scissor so we don't draw anything where we shouldn't
1989 // enable scissor for this frame
1990 const uint32_t height = displayDevice->getHeight();
1991 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
1992 scissor.getWidth(), scissor.getHeight());
1998 * and then, render the layers targeted at the framebuffer
2001 ALOGV("Rendering client layers");
2002 const Transform& displayTransform = displayDevice->getTransform();
2004 // we're using h/w composer
2005 bool firstLayer = true;
2006 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2007 const Region clip(dirty.intersect(
2008 displayTransform.transform(layer->visibleRegion)));
2009 ALOGV("Layer: %s", layer->getName().string());
2010 ALOGV(" Composition type: %s",
2011 to_string(layer->getCompositionType(hwcId)).c_str());
2012 if (!clip.isEmpty()) {
2013 switch (layer->getCompositionType(hwcId)) {
2014 case HWC2::Composition::Cursor:
2015 case HWC2::Composition::Device:
2016 case HWC2::Composition::SolidColor: {
2017 const Layer::State& state(layer->getDrawingState());
2018 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2019 layer->isOpaque(state) && (state.alpha == 1.0f)
2020 && hasClientComposition) {
2021 // never clear the very first layer since we're
2022 // guaranteed the FB is already cleared
2023 layer->clearWithOpenGL(displayDevice, clip);
2027 case HWC2::Composition::Client: {
2028 layer->draw(displayDevice, clip);
2035 ALOGV(" Skipping for empty clip");
2040 // we're not using h/w composer
2041 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2042 const Region clip(dirty.intersect(
2043 displayTransform.transform(layer->visibleRegion)));
2044 if (!clip.isEmpty()) {
2045 layer->draw(displayDevice, clip);
2050 // disable scissor at the end of the frame
2051 mRenderEngine->disableScissor();
2055 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2056 const int32_t height = hw->getHeight();
2057 RenderEngine& engine(getRenderEngine());
2058 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2061 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2062 const sp<IBinder>& handle,
2063 const sp<IGraphicBufferProducer>& gbc,
2064 const sp<Layer>& lbc)
2066 // add this layer to the current state list
2068 Mutex::Autolock _l(mStateLock);
2069 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2072 mCurrentState.layersSortedByZ.add(lbc);
2073 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2076 // attach this layer to the client
2077 client->attachLayer(handle, lbc);
2082 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2083 Mutex::Autolock _l(mStateLock);
2084 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2086 mLayersPendingRemoval.push(layer);
2087 mLayersRemoved = true;
2088 setTransactionFlags(eTransactionNeeded);
2091 return status_t(index);
2094 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2095 return android_atomic_release_load(&mTransactionFlags);
2098 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2099 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2102 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2103 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2104 if ((old & flags)==0) { // wake the server up
2105 signalTransaction();
2110 void SurfaceFlinger::setTransactionState(
2111 const Vector<ComposerState>& state,
2112 const Vector<DisplayState>& displays,
2116 Mutex::Autolock _l(mStateLock);
2117 uint32_t transactionFlags = 0;
2119 if (flags & eAnimation) {
2120 // For window updates that are part of an animation we must wait for
2121 // previous animation "frames" to be handled.
2122 while (mAnimTransactionPending) {
2123 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2124 if (CC_UNLIKELY(err != NO_ERROR)) {
2125 // just in case something goes wrong in SF, return to the
2126 // caller after a few seconds.
2127 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2128 "waiting for previous animation frame");
2129 mAnimTransactionPending = false;
2135 size_t count = displays.size();
2136 for (size_t i=0 ; i<count ; i++) {
2137 const DisplayState& s(displays[i]);
2138 transactionFlags |= setDisplayStateLocked(s);
2141 count = state.size();
2142 for (size_t i=0 ; i<count ; i++) {
2143 const ComposerState& s(state[i]);
2144 // Here we need to check that the interface we're given is indeed
2145 // one of our own. A malicious client could give us a NULL
2146 // IInterface, or one of its own or even one of our own but a
2147 // different type. All these situations would cause us to crash.
2149 // NOTE: it would be better to use RTTI as we could directly check
2150 // that we have a Client*. however, RTTI is disabled in Android.
2151 if (s.client != NULL) {
2152 sp<IBinder> binder = IInterface::asBinder(s.client);
2153 if (binder != NULL) {
2154 String16 desc(binder->getInterfaceDescriptor());
2155 if (desc == ISurfaceComposerClient::descriptor) {
2156 sp<Client> client( static_cast<Client *>(s.client.get()) );
2157 transactionFlags |= setClientStateLocked(client, s.state);
2163 if (transactionFlags) {
2164 // this triggers the transaction
2165 setTransactionFlags(transactionFlags);
2167 // if this is a synchronous transaction, wait for it to take effect
2168 // before returning.
2169 if (flags & eSynchronous) {
2170 mTransactionPending = true;
2172 if (flags & eAnimation) {
2173 mAnimTransactionPending = true;
2175 while (mTransactionPending) {
2176 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2177 if (CC_UNLIKELY(err != NO_ERROR)) {
2178 // just in case something goes wrong in SF, return to the
2179 // called after a few seconds.
2180 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2181 mTransactionPending = false;
2188 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2190 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2195 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2196 if (disp.isValid()) {
2197 const uint32_t what = s.what;
2198 if (what & DisplayState::eSurfaceChanged) {
2199 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2200 disp.surface = s.surface;
2201 flags |= eDisplayTransactionNeeded;
2204 if (what & DisplayState::eLayerStackChanged) {
2205 if (disp.layerStack != s.layerStack) {
2206 disp.layerStack = s.layerStack;
2207 flags |= eDisplayTransactionNeeded;
2210 if (what & DisplayState::eDisplayProjectionChanged) {
2211 if (disp.orientation != s.orientation) {
2212 disp.orientation = s.orientation;
2213 flags |= eDisplayTransactionNeeded;
2215 if (disp.frame != s.frame) {
2216 disp.frame = s.frame;
2217 flags |= eDisplayTransactionNeeded;
2219 if (disp.viewport != s.viewport) {
2220 disp.viewport = s.viewport;
2221 flags |= eDisplayTransactionNeeded;
2224 if (what & DisplayState::eDisplaySizeChanged) {
2225 if (disp.width != s.width) {
2226 disp.width = s.width;
2227 flags |= eDisplayTransactionNeeded;
2229 if (disp.height != s.height) {
2230 disp.height = s.height;
2231 flags |= eDisplayTransactionNeeded;
2238 uint32_t SurfaceFlinger::setClientStateLocked(
2239 const sp<Client>& client,
2240 const layer_state_t& s)
2243 sp<Layer> layer(client->getLayerUser(s.surface));
2245 const uint32_t what = s.what;
2246 if (what & layer_state_t::ePositionChanged) {
2247 if (layer->setPosition(s.x, s.y))
2248 flags |= eTraversalNeeded;
2250 if (what & layer_state_t::eLayerChanged) {
2251 // NOTE: index needs to be calculated before we update the state
2252 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2253 if (layer->setLayer(s.z) && idx >= 0) {
2254 mCurrentState.layersSortedByZ.removeAt(idx);
2255 mCurrentState.layersSortedByZ.add(layer);
2256 // we need traversal (state changed)
2257 // AND transaction (list changed)
2258 flags |= eTransactionNeeded|eTraversalNeeded;
2261 if (what & layer_state_t::eSizeChanged) {
2262 if (layer->setSize(s.w, s.h)) {
2263 flags |= eTraversalNeeded;
2266 if (what & layer_state_t::eAlphaChanged) {
2267 if (layer->setAlpha(s.alpha))
2268 flags |= eTraversalNeeded;
2270 if (what & layer_state_t::eMatrixChanged) {
2271 if (layer->setMatrix(s.matrix))
2272 flags |= eTraversalNeeded;
2274 if (what & layer_state_t::eTransparentRegionChanged) {
2275 if (layer->setTransparentRegionHint(s.transparentRegion))
2276 flags |= eTraversalNeeded;
2278 if (what & layer_state_t::eFlagsChanged) {
2279 if (layer->setFlags(s.flags, s.mask))
2280 flags |= eTraversalNeeded;
2282 if (what & layer_state_t::eCropChanged) {
2283 if (layer->setCrop(s.crop))
2284 flags |= eTraversalNeeded;
2286 if (what & layer_state_t::eFinalCropChanged) {
2287 if (layer->setFinalCrop(s.finalCrop))
2288 flags |= eTraversalNeeded;
2290 if (what & layer_state_t::eLayerStackChanged) {
2291 // NOTE: index needs to be calculated before we update the state
2292 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2293 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
2294 mCurrentState.layersSortedByZ.removeAt(idx);
2295 mCurrentState.layersSortedByZ.add(layer);
2296 // we need traversal (state changed)
2297 // AND transaction (list changed)
2298 flags |= eTransactionNeeded|eTraversalNeeded;
2301 if (what & layer_state_t::eDeferTransaction) {
2302 layer->deferTransactionUntil(s.handle, s.frameNumber);
2303 // We don't trigger a traversal here because if no other state is
2304 // changed, we don't want this to cause any more work
2306 if (what & layer_state_t::eOverrideScalingModeChanged) {
2307 layer->setOverrideScalingMode(s.overrideScalingMode);
2308 // We don't trigger a traversal here because if no other state is
2309 // changed, we don't want this to cause any more work
2315 status_t SurfaceFlinger::createLayer(
2316 const String8& name,
2317 const sp<Client>& client,
2318 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2319 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2321 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2322 if (int32_t(w|h) < 0) {
2323 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2328 status_t result = NO_ERROR;
2332 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2333 case ISurfaceComposerClient::eFXSurfaceNormal:
2334 result = createNormalLayer(client,
2335 name, w, h, flags, format,
2336 handle, gbp, &layer);
2338 case ISurfaceComposerClient::eFXSurfaceDim:
2339 result = createDimLayer(client,
2341 handle, gbp, &layer);
2348 if (result != NO_ERROR) {
2352 result = addClientLayer(client, *handle, *gbp, layer);
2353 if (result != NO_ERROR) {
2357 setTransactionFlags(eTransactionNeeded);
2361 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2362 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2363 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2365 // initialize the surfaces
2367 case PIXEL_FORMAT_TRANSPARENT:
2368 case PIXEL_FORMAT_TRANSLUCENT:
2369 format = PIXEL_FORMAT_RGBA_8888;
2371 case PIXEL_FORMAT_OPAQUE:
2372 format = PIXEL_FORMAT_RGBX_8888;
2376 *outLayer = new Layer(this, client, name, w, h, flags);
2377 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2378 if (err == NO_ERROR) {
2379 *handle = (*outLayer)->getHandle();
2380 *gbp = (*outLayer)->getProducer();
2383 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2387 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2388 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2389 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2391 *outLayer = new LayerDim(this, client, name, w, h, flags);
2392 *handle = (*outLayer)->getHandle();
2393 *gbp = (*outLayer)->getProducer();
2397 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2399 // called by the window manager when it wants to remove a Layer
2400 status_t err = NO_ERROR;
2401 sp<Layer> l(client->getLayerUser(handle));
2403 err = removeLayer(l);
2404 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2405 "error removing layer=%p (%s)", l.get(), strerror(-err));
2410 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2412 // called by ~LayerCleaner() when all references to the IBinder (handle)
2414 status_t err = NO_ERROR;
2415 sp<Layer> l(layer.promote());
2417 err = removeLayer(l);
2418 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2419 "error removing layer=%p (%s)", l.get(), strerror(-err));
2424 // ---------------------------------------------------------------------------
2426 void SurfaceFlinger::onInitializeDisplays() {
2427 // reset screen orientation and use primary layer stack
2428 Vector<ComposerState> state;
2429 Vector<DisplayState> displays;
2431 d.what = DisplayState::eDisplayProjectionChanged |
2432 DisplayState::eLayerStackChanged;
2433 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2435 d.orientation = DisplayState::eOrientationDefault;
2436 d.frame.makeInvalid();
2437 d.viewport.makeInvalid();
2441 setTransactionState(state, displays, 0);
2442 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2444 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2445 const nsecs_t period = activeConfig->getVsyncPeriod();
2446 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2449 void SurfaceFlinger::initializeDisplays() {
2450 class MessageScreenInitialized : public MessageBase {
2451 SurfaceFlinger* flinger;
2453 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2454 virtual bool handler() {
2455 flinger->onInitializeDisplays();
2459 sp<MessageBase> msg = new MessageScreenInitialized(this);
2460 postMessageAsync(msg); // we may be called from main thread, use async message
2463 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2465 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2467 int32_t type = hw->getDisplayType();
2468 int currentMode = hw->getPowerMode();
2470 if (mode == currentMode) {
2471 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2475 hw->setPowerMode(mode);
2476 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2477 ALOGW("Trying to set power mode for virtual display");
2481 if (currentMode == HWC_POWER_MODE_OFF) {
2482 getHwComposer().setPowerMode(type, mode);
2483 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2484 // FIXME: eventthread only knows about the main display right now
2485 mEventThread->onScreenAcquired();
2486 resyncToHardwareVsync(true);
2489 mVisibleRegionsDirty = true;
2490 mHasPoweredOff = true;
2491 repaintEverything();
2492 } else if (mode == HWC_POWER_MODE_OFF) {
2493 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2494 disableHardwareVsync(true); // also cancels any in-progress resync
2496 // FIXME: eventthread only knows about the main display right now
2497 mEventThread->onScreenReleased();
2500 getHwComposer().setPowerMode(type, mode);
2501 mVisibleRegionsDirty = true;
2502 // from this point on, SF will stop drawing on this display
2504 getHwComposer().setPowerMode(type, mode);
2508 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2509 class MessageSetPowerMode: public MessageBase {
2510 SurfaceFlinger& mFlinger;
2511 sp<IBinder> mDisplay;
2514 MessageSetPowerMode(SurfaceFlinger& flinger,
2515 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2516 mDisplay(disp) { mMode = mode; }
2517 virtual bool handler() {
2518 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2520 ALOGE("Attempt to set power mode = %d for null display %p",
2521 mMode, mDisplay.get());
2522 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2523 ALOGW("Attempt to set power mode = %d for virtual display",
2526 mFlinger.setPowerModeInternal(hw, mMode);
2531 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2532 postMessageSync(msg);
2535 // ---------------------------------------------------------------------------
2537 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2541 IPCThreadState* ipc = IPCThreadState::self();
2542 const int pid = ipc->getCallingPid();
2543 const int uid = ipc->getCallingUid();
2544 if ((uid != AID_SHELL) &&
2545 !PermissionCache::checkPermission(sDump, pid, uid)) {
2546 result.appendFormat("Permission Denial: "
2547 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2549 // Try to get the main lock, but give up after one second
2550 // (this would indicate SF is stuck, but we want to be able to
2551 // print something in dumpsys).
2552 status_t err = mStateLock.timedLock(s2ns(1));
2553 bool locked = (err == NO_ERROR);
2555 result.appendFormat(
2556 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2557 "dumping anyways (no locks held)\n", strerror(-err), err);
2560 bool dumpAll = true;
2562 size_t numArgs = args.size();
2564 if ((index < numArgs) &&
2565 (args[index] == String16("--list"))) {
2567 listLayersLocked(args, index, result);
2571 if ((index < numArgs) &&
2572 (args[index] == String16("--latency"))) {
2574 dumpStatsLocked(args, index, result);
2578 if ((index < numArgs) &&
2579 (args[index] == String16("--latency-clear"))) {
2581 clearStatsLocked(args, index, result);
2585 if ((index < numArgs) &&
2586 (args[index] == String16("--dispsync"))) {
2588 mPrimaryDispSync.dump(result);
2592 if ((index < numArgs) &&
2593 (args[index] == String16("--static-screen"))) {
2595 dumpStaticScreenStats(result);
2599 #ifdef ENABLE_FENCE_TRACKING
2600 if ((index < numArgs) &&
2601 (args[index] == String16("--fences"))) {
2603 mFenceTracker.dump(&result);
2610 dumpAllLocked(args, index, result);
2614 mStateLock.unlock();
2617 write(fd, result.string(), result.size());
2621 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2622 size_t& /* index */, String8& result) const
2624 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2625 const size_t count = currentLayers.size();
2626 for (size_t i=0 ; i<count ; i++) {
2627 const sp<Layer>& layer(currentLayers[i]);
2628 result.appendFormat("%s\n", layer->getName().string());
2632 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2633 String8& result) const
2636 if (index < args.size()) {
2637 name = String8(args[index]);
2641 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2642 const nsecs_t period = activeConfig->getVsyncPeriod();
2643 result.appendFormat("%" PRId64 "\n", period);
2645 if (name.isEmpty()) {
2646 mAnimFrameTracker.dumpStats(result);
2648 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2649 const size_t count = currentLayers.size();
2650 for (size_t i=0 ; i<count ; i++) {
2651 const sp<Layer>& layer(currentLayers[i]);
2652 if (name == layer->getName()) {
2653 layer->dumpFrameStats(result);
2659 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2660 String8& /* result */)
2663 if (index < args.size()) {
2664 name = String8(args[index]);
2668 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2669 const size_t count = currentLayers.size();
2670 for (size_t i=0 ; i<count ; i++) {
2671 const sp<Layer>& layer(currentLayers[i]);
2672 if (name.isEmpty() || (name == layer->getName())) {
2673 layer->clearFrameStats();
2677 mAnimFrameTracker.clearStats();
2680 // This should only be called from the main thread. Otherwise it would need
2681 // the lock and should use mCurrentState rather than mDrawingState.
2682 void SurfaceFlinger::logFrameStats() {
2683 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2684 const size_t count = drawingLayers.size();
2685 for (size_t i=0 ; i<count ; i++) {
2686 const sp<Layer>& layer(drawingLayers[i]);
2687 layer->logFrameStats();
2690 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2693 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2695 static const char* config =
2697 #ifdef HAS_CONTEXT_PRIORITY
2698 " HAS_CONTEXT_PRIORITY"
2700 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2701 " NEVER_DEFAULT_TO_ASYNC_MODE"
2703 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2704 " TARGET_DISABLE_TRIPLE_BUFFERING"
2707 result.append(config);
2710 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2712 result.appendFormat("Static screen stats:\n");
2713 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2714 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2715 float percent = 100.0f *
2716 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2717 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2718 b + 1, bucketTimeSec, percent);
2720 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2721 float percent = 100.0f *
2722 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2723 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2724 NUM_BUCKETS - 1, bucketTimeSec, percent);
2727 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2728 String8& result) const
2730 bool colorize = false;
2731 if (index < args.size()
2732 && (args[index] == String16("--color"))) {
2737 Colorizer colorizer(colorize);
2739 // figure out if we're stuck somewhere
2740 const nsecs_t now = systemTime();
2741 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2742 const nsecs_t inTransaction(mDebugInTransaction);
2743 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2744 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2747 * Dump library configuration.
2750 colorizer.bold(result);
2751 result.append("Build configuration:");
2752 colorizer.reset(result);
2753 appendSfConfigString(result);
2754 appendUiConfigString(result);
2755 appendGuiConfigString(result);
2756 result.append("\n");
2758 colorizer.bold(result);
2759 result.append("Sync configuration: ");
2760 colorizer.reset(result);
2761 result.append(SyncFeatures::getInstance().toString());
2762 result.append("\n");
2764 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2766 colorizer.bold(result);
2767 result.append("DispSync configuration: ");
2768 colorizer.reset(result);
2769 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2770 "present offset %d ns (refresh %" PRId64 " ns)",
2771 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2772 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
2773 result.append("\n");
2775 // Dump static screen stats
2776 result.append("\n");
2777 dumpStaticScreenStats(result);
2778 result.append("\n");
2781 * Dump the visible layer list
2783 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2784 const size_t count = currentLayers.size();
2785 colorizer.bold(result);
2786 result.appendFormat("Visible layers (count = %zu)\n", count);
2787 colorizer.reset(result);
2788 for (size_t i=0 ; i<count ; i++) {
2789 const sp<Layer>& layer(currentLayers[i]);
2790 layer->dump(result, colorizer);
2794 * Dump Display state
2797 colorizer.bold(result);
2798 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2799 colorizer.reset(result);
2800 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2801 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2806 * Dump SurfaceFlinger global state
2809 colorizer.bold(result);
2810 result.append("SurfaceFlinger global state:\n");
2811 colorizer.reset(result);
2813 HWComposer& hwc(getHwComposer());
2814 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2816 colorizer.bold(result);
2817 result.appendFormat("EGL implementation : %s\n",
2818 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2819 colorizer.reset(result);
2820 result.appendFormat("%s\n",
2821 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2823 mRenderEngine->dump(result);
2825 hw->undefinedRegion.dump(result, "undefinedRegion");
2826 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2827 hw->getOrientation(), hw->isDisplayOn());
2828 result.appendFormat(
2829 " last eglSwapBuffers() time: %f us\n"
2830 " last transaction time : %f us\n"
2831 " transaction-flags : %08x\n"
2832 " refresh-rate : %f fps\n"
2835 " gpu_to_cpu_unsupported : %d\n"
2837 mLastSwapBufferTime/1000.0,
2838 mLastTransactionTime/1000.0,
2840 1e9 / activeConfig->getVsyncPeriod(),
2841 activeConfig->getDpiX(),
2842 activeConfig->getDpiY(),
2843 !mGpuToCpuSupported);
2845 result.appendFormat(" eglSwapBuffers time: %f us\n",
2846 inSwapBuffersDuration/1000.0);
2848 result.appendFormat(" transaction time: %f us\n",
2849 inTransactionDuration/1000.0);
2854 mEventThread->dump(result);
2857 * Dump HWComposer state
2859 colorizer.bold(result);
2860 result.append("h/w composer state:\n");
2861 colorizer.reset(result);
2862 bool hwcDisabled = mDebugDisableHWC || mDebugRegion || mDaltonize ||
2864 result.appendFormat(" h/w composer %s\n",
2865 hwcDisabled ? "disabled" : "enabled");
2869 * Dump gralloc state
2871 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2875 const Vector< sp<Layer> >&
2876 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2877 // Note: mStateLock is held here
2879 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2880 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2881 dpy = mDisplays.keyAt(i);
2886 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2887 // Just use the primary display so we have something to return
2888 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2890 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2893 bool SurfaceFlinger::startDdmConnection()
2895 void* libddmconnection_dso =
2896 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2897 if (!libddmconnection_dso) {
2900 void (*DdmConnection_start)(const char* name);
2901 DdmConnection_start =
2902 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2903 if (!DdmConnection_start) {
2904 dlclose(libddmconnection_dso);
2907 (*DdmConnection_start)(getServiceName());
2911 status_t SurfaceFlinger::onTransact(
2912 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2915 case CREATE_CONNECTION:
2916 case CREATE_DISPLAY:
2917 case SET_TRANSACTION_STATE:
2919 case CLEAR_ANIMATION_FRAME_STATS:
2920 case GET_ANIMATION_FRAME_STATS:
2921 case SET_POWER_MODE:
2922 case GET_HDR_CAPABILITIES:
2924 // codes that require permission check
2925 IPCThreadState* ipc = IPCThreadState::self();
2926 const int pid = ipc->getCallingPid();
2927 const int uid = ipc->getCallingUid();
2928 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2929 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2930 ALOGE("Permission Denial: "
2931 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2932 return PERMISSION_DENIED;
2936 case CAPTURE_SCREEN:
2938 // codes that require permission check
2939 IPCThreadState* ipc = IPCThreadState::self();
2940 const int pid = ipc->getCallingPid();
2941 const int uid = ipc->getCallingUid();
2942 if ((uid != AID_GRAPHICS) &&
2943 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2944 ALOGE("Permission Denial: "
2945 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2946 return PERMISSION_DENIED;
2952 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2953 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2954 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2955 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2956 IPCThreadState* ipc = IPCThreadState::self();
2957 const int pid = ipc->getCallingPid();
2958 const int uid = ipc->getCallingUid();
2959 ALOGE("Permission Denial: "
2960 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2961 return PERMISSION_DENIED;
2965 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2966 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2968 case 1002: // SHOW_UPDATES
2969 n = data.readInt32();
2970 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2971 invalidateHwcGeometry();
2972 repaintEverything();
2974 case 1004:{ // repaint everything
2975 repaintEverything();
2978 case 1005:{ // force transaction
2979 setTransactionFlags(
2981 eDisplayTransactionNeeded|
2985 case 1006:{ // send empty update
2989 case 1008: // toggle use of hw composer
2990 n = data.readInt32();
2991 mDebugDisableHWC = n ? 1 : 0;
2992 invalidateHwcGeometry();
2993 repaintEverything();
2995 case 1009: // toggle use of transform hint
2996 n = data.readInt32();
2997 mDebugDisableTransformHint = n ? 1 : 0;
2998 invalidateHwcGeometry();
2999 repaintEverything();
3001 case 1010: // interrogate.
3002 reply->writeInt32(0);
3003 reply->writeInt32(0);
3004 reply->writeInt32(mDebugRegion);
3005 reply->writeInt32(0);
3006 reply->writeInt32(mDebugDisableHWC);
3009 Mutex::Autolock _l(mStateLock);
3010 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3011 reply->writeInt32(hw->getPageFlipCount());
3016 n = data.readInt32();
3018 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3019 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3020 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3023 mDaltonizer.setMode(Daltonizer::correction);
3025 mDaltonizer.setMode(Daltonizer::simulation);
3028 invalidateHwcGeometry();
3029 repaintEverything();
3033 // apply a color matrix
3034 n = data.readInt32();
3035 mHasColorMatrix = n ? 1 : 0;
3037 // color matrix is sent as mat3 matrix followed by vec3
3038 // offset, then packed into a mat4 where the last row is
3039 // the offset and extra values are 0
3040 for (size_t i = 0 ; i < 4; i++) {
3041 for (size_t j = 0; j < 4; j++) {
3042 mColorMatrix[i][j] = data.readFloat();
3046 mColorMatrix = mat4();
3048 invalidateHwcGeometry();
3049 repaintEverything();
3052 // This is an experimental interface
3053 // Needs to be shifted to proper binder interface when we productize
3055 n = data.readInt32();
3056 mPrimaryDispSync.setRefreshSkipCount(n);
3060 n = data.readInt32();
3061 mForceFullDamage = static_cast<bool>(n);
3064 case 1018: { // Modify Choreographer's phase offset
3065 n = data.readInt32();
3066 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3069 case 1019: { // Modify SurfaceFlinger's phase offset
3070 n = data.readInt32();
3071 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3079 void SurfaceFlinger::repaintEverything() {
3080 android_atomic_or(1, &mRepaintEverything);
3081 signalTransaction();
3084 // ---------------------------------------------------------------------------
3085 // Capture screen into an IGraphiBufferProducer
3086 // ---------------------------------------------------------------------------
3088 /* The code below is here to handle b/8734824
3090 * We create a IGraphicBufferProducer wrapper that forwards all calls
3091 * from the surfaceflinger thread to the calling binder thread, where they
3092 * are executed. This allows the calling thread in the calling process to be
3093 * reused and not depend on having "enough" binder threads to handle the
3096 class GraphicProducerWrapper : public BBinder, public MessageHandler {
3097 /* Parts of GraphicProducerWrapper are run on two different threads,
3098 * communicating by sending messages via Looper but also by shared member
3099 * data. Coherence maintenance is subtle and in places implicit (ugh).
3101 * Don't rely on Looper's sendMessage/handleMessage providing
3102 * release/acquire semantics for any data not actually in the Message.
3103 * Data going from surfaceflinger to binder threads needs to be
3104 * synchronized explicitly.
3106 * Barrier open/wait do provide release/acquire semantics. This provides
3107 * implicit synchronization for data coming back from binder to
3108 * surfaceflinger threads.
3111 sp<IGraphicBufferProducer> impl;
3127 * Called on surfaceflinger thread. This is called by our "fake"
3128 * BpGraphicBufferProducer. We package the data and reply Parcel and
3129 * forward them to the binder thread.
3131 virtual status_t transact(uint32_t code,
3132 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3135 this->reply = reply;
3137 // if we've exited, we run the message synchronously right here.
3138 // note (JH): as far as I can tell from looking at the code, this
3139 // never actually happens. if it does, i'm not sure if it happens
3140 // on the surfaceflinger or binder thread.
3141 handleMessage(Message(MSG_API_CALL));
3144 // Prevent stores to this->{code, data, reply} from being
3145 // reordered later than the construction of Message.
3146 atomic_thread_fence(memory_order_release);
3147 looper->sendMessage(this, Message(MSG_API_CALL));
3154 * here we run on the binder thread. All we've got to do is
3155 * call the real BpGraphicBufferProducer.
3157 virtual void handleMessage(const Message& message) {
3158 int what = message.what;
3159 // Prevent reads below from happening before the read from Message
3160 atomic_thread_fence(memory_order_acquire);
3161 if (what == MSG_API_CALL) {
3162 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3164 } else if (what == MSG_EXIT) {
3165 exitRequested = true;
3170 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3172 looper(new Looper(true)),
3175 exitRequested(false),
3182 status_t waitForResponse() {
3184 looper->pollOnce(-1);
3185 } while (!exitRequested);
3190 void exit(status_t result) {
3191 this->result = result;
3193 // Ensure this->result is visible to the binder thread before it
3194 // handles the message.
3195 atomic_thread_fence(memory_order_release);
3196 looper->sendMessage(this, Message(MSG_EXIT));
3201 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3202 const sp<IGraphicBufferProducer>& producer,
3203 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3204 uint32_t minLayerZ, uint32_t maxLayerZ,
3205 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3207 if (CC_UNLIKELY(display == 0))
3210 if (CC_UNLIKELY(producer == 0))
3213 // if we have secure windows on this display, never allow the screen capture
3214 // unless the producer interface is local (i.e.: we can take a screenshot for
3216 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3218 // Convert to surfaceflinger's internal rotation type.
3219 Transform::orientation_flags rotationFlags;
3221 case ISurfaceComposer::eRotateNone:
3222 rotationFlags = Transform::ROT_0;
3224 case ISurfaceComposer::eRotate90:
3225 rotationFlags = Transform::ROT_90;
3227 case ISurfaceComposer::eRotate180:
3228 rotationFlags = Transform::ROT_180;
3230 case ISurfaceComposer::eRotate270:
3231 rotationFlags = Transform::ROT_270;
3234 rotationFlags = Transform::ROT_0;
3235 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3239 class MessageCaptureScreen : public MessageBase {
3240 SurfaceFlinger* flinger;
3241 sp<IBinder> display;
3242 sp<IGraphicBufferProducer> producer;
3244 uint32_t reqWidth, reqHeight;
3245 uint32_t minLayerZ,maxLayerZ;
3246 bool useIdentityTransform;
3247 Transform::orientation_flags rotation;
3249 bool isLocalScreenshot;
3251 MessageCaptureScreen(SurfaceFlinger* flinger,
3252 const sp<IBinder>& display,
3253 const sp<IGraphicBufferProducer>& producer,
3254 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3255 uint32_t minLayerZ, uint32_t maxLayerZ,
3256 bool useIdentityTransform,
3257 Transform::orientation_flags rotation,
3258 bool isLocalScreenshot)
3259 : flinger(flinger), display(display), producer(producer),
3260 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3261 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3262 useIdentityTransform(useIdentityTransform),
3263 rotation(rotation), result(PERMISSION_DENIED),
3264 isLocalScreenshot(isLocalScreenshot)
3267 status_t getResult() const {
3270 virtual bool handler() {
3271 Mutex::Autolock _l(flinger->mStateLock);
3272 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3273 result = flinger->captureScreenImplLocked(hw, producer,
3274 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3275 useIdentityTransform, rotation, isLocalScreenshot);
3276 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3281 // make sure to process transactions before screenshots -- a transaction
3282 // might already be pending but scheduled for VSYNC; this guarantees we
3283 // will handle it before the screenshot. When VSYNC finally arrives
3284 // the scheduled transaction will be a no-op. If no transactions are
3285 // scheduled at this time, this will end-up being a no-op as well.
3286 mEventQueue.invalidateTransactionNow();
3288 // this creates a "fake" BBinder which will serve as a "fake" remote
3289 // binder to receive the marshaled calls and forward them to the
3290 // real remote (a BpGraphicBufferProducer)
3291 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3293 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3294 // which does the marshaling work forwards to our "fake remote" above.
3295 sp<MessageBase> msg = new MessageCaptureScreen(this,
3296 display, IGraphicBufferProducer::asInterface( wrapper ),
3297 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3298 useIdentityTransform, rotationFlags, isLocalScreenshot);
3300 status_t res = postMessageAsync(msg);
3301 if (res == NO_ERROR) {
3302 res = wrapper->waitForResponse();
3308 void SurfaceFlinger::renderScreenImplLocked(
3309 const sp<const DisplayDevice>& hw,
3310 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3311 uint32_t minLayerZ, uint32_t maxLayerZ,
3312 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3315 RenderEngine& engine(getRenderEngine());
3317 // get screen geometry
3318 const int32_t hw_w = hw->getWidth();
3319 const int32_t hw_h = hw->getHeight();
3320 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3321 static_cast<int32_t>(reqHeight) != hw_h;
3323 // if a default or invalid sourceCrop is passed in, set reasonable values
3324 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3325 !sourceCrop.isValid()) {
3326 sourceCrop.setLeftTop(Point(0, 0));
3327 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3330 // ensure that sourceCrop is inside screen
3331 if (sourceCrop.left < 0) {
3332 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3334 if (sourceCrop.right > hw_w) {
3335 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3337 if (sourceCrop.top < 0) {
3338 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3340 if (sourceCrop.bottom > hw_h) {
3341 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3344 // make sure to clear all GL error flags
3345 engine.checkErrors();
3347 // set-up our viewport
3348 engine.setViewportAndProjection(
3349 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3350 engine.disableTexturing();
3352 // redraw the screen entirely...
3353 engine.clearWithColor(0, 0, 0, 1);
3355 const LayerVector& layers( mDrawingState.layersSortedByZ );
3356 const size_t count = layers.size();
3357 for (size_t i=0 ; i<count ; ++i) {
3358 const sp<Layer>& layer(layers[i]);
3359 const Layer::State& state(layer->getDrawingState());
3360 if (state.layerStack == hw->getLayerStack()) {
3361 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3362 if (layer->isVisible()) {
3363 if (filtering) layer->setFiltering(true);
3364 layer->draw(hw, useIdentityTransform);
3365 if (filtering) layer->setFiltering(false);
3371 hw->setViewportAndProjection();
3375 status_t SurfaceFlinger::captureScreenImplLocked(
3376 const sp<const DisplayDevice>& hw,
3377 const sp<IGraphicBufferProducer>& producer,
3378 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3379 uint32_t minLayerZ, uint32_t maxLayerZ,
3380 bool useIdentityTransform, Transform::orientation_flags rotation,
3381 bool isLocalScreenshot)
3385 // get screen geometry
3386 uint32_t hw_w = hw->getWidth();
3387 uint32_t hw_h = hw->getHeight();
3389 if (rotation & Transform::ROT_90) {
3390 std::swap(hw_w, hw_h);
3393 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3394 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3395 reqWidth, reqHeight, hw_w, hw_h);
3399 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3400 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3402 bool secureLayerIsVisible = false;
3403 const LayerVector& layers(mDrawingState.layersSortedByZ);
3404 const size_t count = layers.size();
3405 for (size_t i = 0 ; i < count ; ++i) {
3406 const sp<Layer>& layer(layers[i]);
3407 const Layer::State& state(layer->getDrawingState());
3408 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3409 state.z <= maxLayerZ && layer->isVisible() &&
3410 layer->isSecure()) {
3411 secureLayerIsVisible = true;
3415 if (!isLocalScreenshot && secureLayerIsVisible) {
3416 ALOGW("FB is protected: PERMISSION_DENIED");
3417 return PERMISSION_DENIED;
3420 // create a surface (because we're a producer, and we need to
3421 // dequeue/queue a buffer)
3422 sp<Surface> sur = new Surface(producer, false);
3423 ANativeWindow* window = sur.get();
3425 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3426 if (result == NO_ERROR) {
3427 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3428 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3431 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3432 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3433 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3434 err |= native_window_set_usage(window, usage);
3436 if (err == NO_ERROR) {
3437 ANativeWindowBuffer* buffer;
3438 /* TODO: Once we have the sync framework everywhere this can use
3439 * server-side waits on the fence that dequeueBuffer returns.
3441 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3442 if (result == NO_ERROR) {
3444 // create an EGLImage from the buffer so we can later
3445 // turn it into a texture
3446 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3447 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3448 if (image != EGL_NO_IMAGE_KHR) {
3449 // this binds the given EGLImage as a framebuffer for the
3450 // duration of this scope.
3451 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3452 if (imageBond.getStatus() == NO_ERROR) {
3453 // this will in fact render into our dequeued buffer
3454 // via an FBO, which means we didn't have to create
3455 // an EGLSurface and therefore we're not
3456 // dependent on the context's EGLConfig.
3457 renderScreenImplLocked(
3458 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3459 useIdentityTransform, rotation);
3461 // Attempt to create a sync khr object that can produce a sync point. If that
3462 // isn't available, create a non-dupable sync object in the fallback path and
3463 // wait on it directly.
3465 if (!DEBUG_SCREENSHOTS) {
3466 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3467 // native fence fd will not be populated until flush() is done.
3468 getRenderEngine().flush();
3470 sync = EGL_NO_SYNC_KHR;
3472 if (sync != EGL_NO_SYNC_KHR) {
3474 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3475 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3476 ALOGW("captureScreen: failed to dup sync khr object");
3479 eglDestroySyncKHR(mEGLDisplay, sync);
3482 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3483 if (sync != EGL_NO_SYNC_KHR) {
3484 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3485 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3486 EGLint eglErr = eglGetError();
3487 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3488 ALOGW("captureScreen: fence wait timed out");
3490 ALOGW_IF(eglErr != EGL_SUCCESS,
3491 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3493 eglDestroySyncKHR(mEGLDisplay, sync);
3495 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3498 if (DEBUG_SCREENSHOTS) {
3499 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3500 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3501 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3502 hw, minLayerZ, maxLayerZ);
3507 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3508 result = INVALID_OPERATION;
3509 window->cancelBuffer(window, buffer, syncFd);
3512 // destroy our image
3513 eglDestroyImageKHR(mEGLDisplay, image);
3518 // queueBuffer takes ownership of syncFd
3519 result = window->queueBuffer(window, buffer, syncFd);
3525 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3531 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3532 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3533 if (DEBUG_SCREENSHOTS) {
3534 for (size_t y=0 ; y<h ; y++) {
3535 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3536 for (size_t x=0 ; x<w ; x++) {
3537 if (p[x] != 0xFF000000) return;
3540 ALOGE("*** we just took a black screenshot ***\n"
3541 "requested minz=%d, maxz=%d, layerStack=%d",
3542 minLayerZ, maxLayerZ, hw->getLayerStack());
3543 const LayerVector& layers( mDrawingState.layersSortedByZ );
3544 const size_t count = layers.size();
3545 for (size_t i=0 ; i<count ; ++i) {
3546 const sp<Layer>& layer(layers[i]);
3547 const Layer::State& state(layer->getDrawingState());
3548 const bool visible = (state.layerStack == hw->getLayerStack())
3549 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3550 && (layer->isVisible());
3551 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
3552 visible ? '+' : '-',
3553 i, layer->getName().string(), state.layerStack, state.z,
3554 layer->isVisible(), state.flags, state.alpha);
3559 // ---------------------------------------------------------------------------
3561 SurfaceFlinger::LayerVector::LayerVector() {
3564 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3565 : SortedVector<sp<Layer> >(rhs) {
3568 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3569 const void* rhs) const
3571 // sort layers per layer-stack, then by z-order and finally by sequence
3572 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3573 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3575 uint32_t ls = l->getCurrentState().layerStack;
3576 uint32_t rs = r->getCurrentState().layerStack;
3580 uint32_t lz = l->getCurrentState().z;
3581 uint32_t rz = r->getCurrentState().z;
3585 return l->sequence - r->sequence;
3588 // ---------------------------------------------------------------------------
3590 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3591 : type(DisplayDevice::DISPLAY_ID_INVALID),
3592 layerStack(DisplayDevice::NO_LAYER_STACK),
3599 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3600 DisplayDevice::DisplayType type, bool isSecure)
3602 layerStack(DisplayDevice::NO_LAYER_STACK),
3606 isSecure(isSecure) {
3607 viewport.makeInvalid();
3608 frame.makeInvalid();
3611 // ---------------------------------------------------------------------------
3613 }; // namespace android
3616 #if defined(__gl_h_)
3617 #error "don't include gl/gl.h in this file"
3620 #if defined(__gl2_h_)
3621 #error "don't include gl2/gl2.h in this file"