2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 #include <sys/types.h>
25 #include <stdatomic.h>
29 #include <cutils/log.h>
30 #include <cutils/properties.h>
32 #include <binder/IPCThreadState.h>
33 #include <binder/IServiceManager.h>
34 #include <binder/MemoryHeapBase.h>
35 #include <binder/PermissionCache.h>
37 #include <ui/DisplayInfo.h>
38 #include <ui/DisplayStatInfo.h>
40 #include <gui/BitTube.h>
41 #include <gui/BufferQueue.h>
42 #include <gui/GuiConfig.h>
43 #include <gui/IDisplayEventConnection.h>
44 #include <gui/Surface.h>
45 #include <gui/GraphicBufferAlloc.h>
47 #include <ui/GraphicBufferAllocator.h>
48 #include <ui/PixelFormat.h>
49 #include <ui/UiConfig.h>
51 #include <utils/misc.h>
52 #include <utils/String8.h>
53 #include <utils/String16.h>
54 #include <utils/StopWatch.h>
55 #include <utils/Trace.h>
57 #include <private/android_filesystem_config.h>
58 #include <private/gui/SyncFeatures.h>
62 #include "Colorizer.h"
63 #include "DdmConnection.h"
64 #include "DisplayDevice.h"
66 #include "EventControlThread.h"
67 #include "EventThread.h"
70 #include "SurfaceFlinger.h"
72 #include "DisplayHardware/FramebufferSurface.h"
73 #include "DisplayHardware/HWComposer.h"
74 #include "DisplayHardware/VirtualDisplaySurface.h"
76 #include "Effects/Daltonizer.h"
78 #include "RenderEngine/RenderEngine.h"
79 #include <cutils/compiler.h>
80 #include "DisplayUtils.h"
82 #define DISPLAY_COUNT 1
85 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 #define DEBUG_SCREENSHOTS false
90 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
94 // This is the phase offset in nanoseconds of the software vsync event
95 // relative to the vsync event reported by HWComposer. The software vsync
96 // event is when SurfaceFlinger and Choreographer-based applications run each
99 // This phase offset allows adjustment of the minimum latency from application
100 // wake-up (by Choregographer) time to the time at which the resulting window
101 // image is displayed. This value may be either positive (after the HW vsync)
102 // or negative (before the HW vsync). Setting it to 0 will result in a
103 // minimum latency of two vsync periods because the app and SurfaceFlinger
104 // will run just after the HW vsync. Setting it to a positive number will
105 // result in the minimum latency being:
107 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
109 // Note that reducing this latency makes it more likely for the applications
110 // to not have their window content image ready in time. When this happens
111 // the latency will end up being an additional vsync period, and animations
112 // will hiccup. Therefore, this latency should be tuned somewhat
113 // conservatively (or at least with awareness of the trade-off being made).
114 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
116 // This is the phase offset at which SurfaceFlinger's composition runs.
117 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
119 // ---------------------------------------------------------------------------
121 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
122 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
123 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
124 const String16 sDump("android.permission.DUMP");
126 // ---------------------------------------------------------------------------
128 SurfaceFlinger::SurfaceFlinger()
129 : BnSurfaceComposer(),
130 mTransactionFlags(0),
131 mTransactionPending(false),
132 mAnimTransactionPending(false),
133 mLayersRemoved(false),
134 mRepaintEverything(0),
136 mBootTime(systemTime()),
137 mVisibleRegionsDirty(false),
138 mHwWorkListDirty(false),
139 mAnimCompositionPending(false),
143 mDebugDisableTransformHint(0),
144 mDebugInSwapBuffers(0),
145 mLastSwapBufferTime(0),
146 mDebugInTransaction(0),
147 mLastTransactionTime(0),
148 mBootFinished(false),
149 mForceFullDamage(false),
150 mPrimaryHWVsyncEnabled(false),
151 mHWVsyncAvailable(false),
153 mHasColorMatrix(false),
154 mHasPoweredOff(false),
159 ALOGI("SurfaceFlinger is starting");
161 // debugging stuff...
162 char value[PROPERTY_VALUE_MAX];
164 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
165 mGpuToCpuSupported = !atoi(value);
167 property_get("debug.sf.showupdates", value, "0");
168 mDebugRegion = atoi(value);
170 property_get("debug.sf.ddms", value, "0");
171 mDebugDDMS = atoi(value);
173 if (!startDdmConnection()) {
174 // start failed, and DDMS debugging not enabled
178 ALOGI_IF(mDebugRegion, "showupdates enabled");
179 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
182 void SurfaceFlinger::onFirstRef()
184 mEventQueue.init(this);
187 SurfaceFlinger::~SurfaceFlinger()
189 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
190 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
191 eglTerminate(display);
194 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
196 // the window manager died on us. prepare its eulogy.
198 // restore initial conditions (default device unblank, etc)
199 initializeDisplays();
201 // restart the boot-animation
205 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
207 sp<ISurfaceComposerClient> bclient;
208 sp<Client> client(new Client(this));
209 status_t err = client->initCheck();
210 if (err == NO_ERROR) {
216 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
219 class DisplayToken : public BBinder {
220 sp<SurfaceFlinger> flinger;
221 virtual ~DisplayToken() {
222 // no more references, this display must be terminated
223 Mutex::Autolock _l(flinger->mStateLock);
224 flinger->mCurrentState.displays.removeItem(this);
225 flinger->setTransactionFlags(eDisplayTransactionNeeded);
228 DisplayToken(const sp<SurfaceFlinger>& flinger)
233 sp<BBinder> token = new DisplayToken(this);
235 Mutex::Autolock _l(mStateLock);
236 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
237 info.displayName = displayName;
238 info.isSecure = secure;
239 mCurrentState.displays.add(token, info);
244 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
245 Mutex::Autolock _l(mStateLock);
247 ssize_t idx = mCurrentState.displays.indexOfKey(display);
249 ALOGW("destroyDisplay: invalid display token");
253 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
254 if (!info.isVirtualDisplay()) {
255 ALOGE("destroyDisplay called for non-virtual display");
259 mCurrentState.displays.removeItemsAt(idx);
260 setTransactionFlags(eDisplayTransactionNeeded);
263 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
264 ALOGW_IF(mBuiltinDisplays[type],
265 "Overwriting display token for display type %d", type);
266 mBuiltinDisplays[type] = new BBinder();
267 DisplayDeviceState info(type);
268 // All non-virtual displays are currently considered secure.
269 info.isSecure = true;
270 mCurrentState.displays.add(mBuiltinDisplays[type], info);
273 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
274 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
275 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
278 return mBuiltinDisplays[id];
281 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
283 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
287 void SurfaceFlinger::bootFinished()
289 const nsecs_t now = systemTime();
290 const nsecs_t duration = now - mBootTime;
291 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
292 mBootFinished = true;
294 // wait patiently for the window manager death
295 const String16 name("window");
296 sp<IBinder> window(defaultServiceManager()->getService(name));
298 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
301 // stop boot animation
302 // formerly we would just kill the process, but we now ask it to exit so it
303 // can choose where to stop the animation.
304 property_set("service.bootanim.exit", "1");
307 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
308 class MessageDestroyGLTexture : public MessageBase {
309 RenderEngine& engine;
312 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
313 : engine(engine), texture(texture) {
315 virtual bool handler() {
316 engine.deleteTextures(1, &texture);
320 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
323 class DispSyncSource : public VSyncSource, private DispSync::Callback {
325 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
328 mTraceVsync(traceVsync),
329 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
330 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
335 mPhaseOffset(phaseOffset),
338 virtual ~DispSyncSource() {}
340 virtual void setVSyncEnabled(bool enable) {
341 Mutex::Autolock lock(mVsyncMutex);
343 status_t err = mDispSync->addEventListener(mPhaseOffset,
344 static_cast<DispSync::Callback*>(this));
345 if (err != NO_ERROR) {
346 ALOGE("error registering vsync callback: %s (%d)",
347 strerror(-err), err);
349 //ATRACE_INT(mVsyncOnLabel.string(), 1);
351 status_t err = mDispSync->removeEventListener(
352 static_cast<DispSync::Callback*>(this));
353 if (err != NO_ERROR) {
354 ALOGE("error unregistering vsync callback: %s (%d)",
355 strerror(-err), err);
357 //ATRACE_INT(mVsyncOnLabel.string(), 0);
362 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
363 Mutex::Autolock lock(mCallbackMutex);
364 mCallback = callback;
367 virtual void setPhaseOffset(nsecs_t phaseOffset) {
368 Mutex::Autolock lock(mVsyncMutex);
370 // Normalize phaseOffset to [0, period)
371 auto period = mDispSync->getPeriod();
372 phaseOffset %= period;
373 if (phaseOffset < 0) {
374 // If we're here, then phaseOffset is in (-period, 0). After this
375 // operation, it will be in (0, period)
376 phaseOffset += period;
378 mPhaseOffset = phaseOffset;
380 // If we're not enabled, we don't need to mess with the listeners
385 // Remove the listener with the old offset
386 status_t err = mDispSync->removeEventListener(
387 static_cast<DispSync::Callback*>(this));
388 if (err != NO_ERROR) {
389 ALOGE("error unregistering vsync callback: %s (%d)",
390 strerror(-err), err);
393 // Add a listener with the new offset
394 err = mDispSync->addEventListener(mPhaseOffset,
395 static_cast<DispSync::Callback*>(this));
396 if (err != NO_ERROR) {
397 ALOGE("error registering vsync callback: %s (%d)",
398 strerror(-err), err);
403 virtual void onDispSyncEvent(nsecs_t when) {
404 sp<VSyncSource::Callback> callback;
406 Mutex::Autolock lock(mCallbackMutex);
407 callback = mCallback;
410 mValue = (mValue + 1) % 2;
411 ATRACE_INT(mVsyncEventLabel.string(), mValue);
415 if (callback != NULL) {
416 callback->onVSyncEvent(when);
422 const bool mTraceVsync;
423 const String8 mVsyncOnLabel;
424 const String8 mVsyncEventLabel;
428 Mutex mCallbackMutex; // Protects the following
429 sp<VSyncSource::Callback> mCallback;
431 Mutex mVsyncMutex; // Protects the following
432 nsecs_t mPhaseOffset;
436 void SurfaceFlinger::init() {
437 ALOGI( "SurfaceFlinger's main thread ready to run. "
438 "Initializing graphics H/W...");
440 Mutex::Autolock _l(mStateLock);
442 // initialize EGL for the default display
443 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
444 eglInitialize(mEGLDisplay, NULL, NULL);
446 // Initialize the H/W composer object. There may or may not be an
447 // actual hardware composer underneath.
448 mHwc = DisplayUtils::getInstance()->getHWCInstance(this,
449 *static_cast<HWComposer::EventHandler *>(this));
451 // get a RenderEngine for the given display / config (can't fail)
452 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
454 // retrieve the EGL context that was selected/created
455 mEGLContext = mRenderEngine->getEGLContext();
457 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
458 "couldn't create EGLContext");
460 // initialize our non-virtual displays
461 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
462 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
463 // set-up the displays that are already connected
464 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
465 // All non-virtual displays are currently considered secure.
466 bool isSecure = true;
467 createBuiltinDisplayLocked(type);
468 wp<IBinder> token = mBuiltinDisplays[i];
470 sp<IGraphicBufferProducer> producer;
471 sp<IGraphicBufferConsumer> consumer;
472 BufferQueue::createBufferQueue(&producer, &consumer,
473 new GraphicBufferAlloc());
475 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
477 int32_t hwcId = allocateHwcDisplayId(type);
478 sp<DisplayDevice> hw = new DisplayDevice(this,
479 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
481 mRenderEngine->getEGLConfig());
482 if (i > DisplayDevice::DISPLAY_PRIMARY) {
483 // FIXME: currently we don't get blank/unblank requests
484 // for displays other than the main display, so we always
485 // assume a connected display is unblanked.
486 ALOGD("marking display %zu as acquired/unblanked", i);
487 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
489 // When a non-virtual display device is added at boot time,
490 // update the active config by querying HWC otherwise the
491 // default config (config 0) will be used.
492 int activeConfig = mHwc->getActiveConfig(hwcId);
493 if (activeConfig >= 0) {
494 hw->setActiveConfig(activeConfig);
496 mDisplays.add(token, hw);
500 // make the GLContext current so that we can create textures when creating Layers
501 // (which may happens before we render something)
502 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
504 // start the EventThread
505 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
506 vsyncPhaseOffsetNs, true, "app");
507 mEventThread = new EventThread(vsyncSrc);
508 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
509 sfVsyncPhaseOffsetNs, true, "sf");
510 mSFEventThread = new EventThread(sfVsyncSrc);
511 mEventQueue.setEventThread(mSFEventThread);
513 mEventControlThread = new EventControlThread(this);
514 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
516 // set a fake vsync period if there is no HWComposer
517 if (mHwc->initCheck() != NO_ERROR) {
518 mPrimaryDispSync.setPeriod(16666667);
521 // initialize our drawing state
522 mDrawingState = mCurrentState;
524 // set initial conditions (e.g. unblank default device)
525 initializeDisplays();
527 // start boot animation
531 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
532 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
533 type : mHwc->allocateDisplayId();
536 void SurfaceFlinger::startBootAnim() {
537 // start boot animation
538 property_set("service.bootanim.exit", "0");
539 property_set("ctl.start", "bootanim");
542 size_t SurfaceFlinger::getMaxTextureSize() const {
543 return mRenderEngine->getMaxTextureSize();
546 size_t SurfaceFlinger::getMaxViewportDims() const {
547 return mRenderEngine->getMaxViewportDims();
550 // ----------------------------------------------------------------------------
552 bool SurfaceFlinger::authenticateSurfaceTexture(
553 const sp<IGraphicBufferProducer>& bufferProducer) const {
554 Mutex::Autolock _l(mStateLock);
555 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
556 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
559 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
560 Vector<DisplayInfo>* configs) {
561 if ((configs == NULL) || (display.get() == NULL)) {
566 return NAME_NOT_FOUND;
568 int32_t type = NAME_NOT_FOUND;
569 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
570 if (display == mBuiltinDisplays[i]) {
580 // TODO: Not sure if display density should handled by SF any longer
582 static int getDensityFromProperty(char const* propName) {
583 char property[PROPERTY_VALUE_MAX];
585 if (property_get(propName, property, NULL) > 0) {
586 density = atoi(property);
591 static int getEmuDensity() {
592 return getDensityFromProperty("qemu.sf.lcd_density"); }
593 static int getBuildDensity() {
594 return getDensityFromProperty("ro.sf.lcd_density"); }
599 const Vector<HWComposer::DisplayConfig>& hwConfigs =
600 getHwComposer().getConfigs(type);
601 for (size_t c = 0; c < hwConfigs.size(); ++c) {
602 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
603 DisplayInfo info = DisplayInfo();
605 float xdpi = hwConfig.xdpi;
606 float ydpi = hwConfig.ydpi;
608 if (type == DisplayDevice::DISPLAY_PRIMARY) {
609 // The density of the device is provided by a build property
610 float density = Density::getBuildDensity() / 160.0f;
612 // the build doesn't provide a density -- this is wrong!
614 ALOGE("ro.sf.lcd_density must be defined as a build property");
615 density = xdpi / 160.0f;
617 if (Density::getEmuDensity()) {
618 // if "qemu.sf.lcd_density" is specified, it overrides everything
619 xdpi = ydpi = density = Density::getEmuDensity();
622 info.density = density;
624 // TODO: this needs to go away (currently needed only by webkit)
625 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
626 info.orientation = hw->getOrientation();
628 // TODO: where should this value come from?
629 static const int TV_DENSITY = 213;
630 info.density = TV_DENSITY / 160.0f;
631 info.orientation = 0;
634 info.w = hwConfig.width;
635 info.h = hwConfig.height;
638 info.fps = float(1e9 / hwConfig.refresh);
639 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
641 // This is how far in advance a buffer must be queued for
642 // presentation at a given time. If you want a buffer to appear
643 // on the screen at time N, you must submit the buffer before
644 // (N - presentationDeadline).
646 // Normally it's one full refresh period (to give SF a chance to
647 // latch the buffer), but this can be reduced by configuring a
648 // DispSync offset. Any additional delays introduced by the hardware
649 // composer or panel must be accounted for here.
651 // We add an additional 1ms to allow for processing time and
652 // differences between the ideal and actual refresh rate.
653 info.presentationDeadline =
654 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
656 // All non-virtual displays are currently considered secure.
659 configs->push_back(info);
665 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
666 DisplayStatInfo* stats) {
671 // FIXME for now we always return stats for the primary display
672 memset(stats, 0, sizeof(*stats));
673 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
674 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
678 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
679 sp<DisplayDevice> device(getDisplayDevice(display));
680 if (device != NULL) {
681 return device->getActiveConfig();
686 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
687 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
689 int32_t type = hw->getDisplayType();
690 int currentMode = hw->getActiveConfig();
692 if (mode == currentMode) {
693 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
697 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
698 ALOGW("Trying to set config for virtual display");
702 status_t status = getHwComposer().setActiveConfig(type, mode);
703 if (status == NO_ERROR) {
704 hw->setActiveConfig(mode);
708 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
709 class MessageSetActiveConfig: public MessageBase {
710 SurfaceFlinger& mFlinger;
711 sp<IBinder> mDisplay;
714 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
716 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
717 virtual bool handler() {
718 Vector<DisplayInfo> configs;
719 mFlinger.getDisplayConfigs(mDisplay, &configs);
720 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
721 ALOGE("Attempt to set active config = %d for display with %zu configs",
722 mMode, configs.size());
724 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
726 ALOGE("Attempt to set active config = %d for null display %p",
727 mMode, mDisplay.get());
728 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
729 ALOGW("Attempt to set active config = %d for virtual display",
732 mFlinger.setActiveConfigInternal(hw, mMode);
737 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
738 postMessageSync(msg);
742 status_t SurfaceFlinger::clearAnimationFrameStats() {
743 Mutex::Autolock _l(mStateLock);
744 mAnimFrameTracker.clearStats();
748 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
749 Mutex::Autolock _l(mStateLock);
750 mAnimFrameTracker.getStats(outStats);
754 // ----------------------------------------------------------------------------
756 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
757 return mEventThread->createEventConnection();
760 // ----------------------------------------------------------------------------
762 void SurfaceFlinger::waitForEvent() {
763 mEventQueue.waitMessage();
766 void SurfaceFlinger::signalTransaction() {
767 mEventQueue.invalidate();
770 void SurfaceFlinger::signalLayerUpdate() {
771 mEventQueue.invalidate();
774 void SurfaceFlinger::signalRefresh() {
775 mEventQueue.refresh();
778 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
779 nsecs_t reltime, uint32_t /* flags */) {
780 return mEventQueue.postMessage(msg, reltime);
783 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
784 nsecs_t reltime, uint32_t /* flags */) {
785 status_t res = mEventQueue.postMessage(msg, reltime);
786 if (res == NO_ERROR) {
792 void SurfaceFlinger::run() {
798 void SurfaceFlinger::enableHardwareVsync() {
799 Mutex::Autolock _l(mHWVsyncLock);
800 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
801 mPrimaryDispSync.beginResync();
802 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
803 mEventControlThread->setVsyncEnabled(true);
804 mPrimaryHWVsyncEnabled = true;
808 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
809 Mutex::Autolock _l(mHWVsyncLock);
812 mHWVsyncAvailable = true;
813 } else if (!mHWVsyncAvailable) {
814 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
818 const nsecs_t period =
819 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
821 mPrimaryDispSync.reset();
822 mPrimaryDispSync.setPeriod(period);
824 if (!mPrimaryHWVsyncEnabled) {
825 mPrimaryDispSync.beginResync();
826 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
827 mEventControlThread->setVsyncEnabled(true);
828 mPrimaryHWVsyncEnabled = true;
832 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
833 Mutex::Autolock _l(mHWVsyncLock);
834 if (mPrimaryHWVsyncEnabled) {
835 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
836 mEventControlThread->setVsyncEnabled(false);
837 mPrimaryDispSync.endResync();
838 mPrimaryHWVsyncEnabled = false;
840 if (makeUnavailable) {
841 mHWVsyncAvailable = false;
845 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
846 bool needsHwVsync = false;
848 { // Scope for the lock
849 Mutex::Autolock _l(mHWVsyncLock);
850 if (type == 0 && mPrimaryHWVsyncEnabled) {
851 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
856 enableHardwareVsync();
858 disableHardwareVsync(false);
862 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
863 if (mEventThread == NULL) {
864 // This is a temporary workaround for b/7145521. A non-null pointer
865 // does not mean EventThread has finished initializing, so this
866 // is not a correct fix.
867 ALOGW("WARNING: EventThread not started, ignoring hotplug");
871 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
872 Mutex::Autolock _l(mStateLock);
874 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
876 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
877 mBuiltinDisplays[type].clear();
878 updateVisibleRegionsDirty();
880 setTransactionFlags(eDisplayTransactionNeeded);
882 // Defer EventThread notification until SF has updated mDisplays.
886 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
888 getHwComposer().eventControl(disp, event, enabled);
891 void SurfaceFlinger::onMessageReceived(int32_t what) {
894 case MessageQueue::TRANSACTION: {
895 handleMessageTransaction();
898 case MessageQueue::INVALIDATE: {
899 bool refreshNeeded = handleMessageTransaction();
900 refreshNeeded |= handleMessageInvalidate();
901 refreshNeeded |= mRepaintEverything;
903 // Signal a refresh if a transaction modified the window state,
904 // a new buffer was latched, or if HWC has requested a full
910 case MessageQueue::REFRESH: {
911 handleMessageRefresh();
917 bool SurfaceFlinger::handleMessageTransaction() {
918 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
919 if (transactionFlags) {
920 handleTransaction(transactionFlags);
926 bool SurfaceFlinger::handleMessageInvalidate() {
928 return handlePageFlip();
931 void SurfaceFlinger::handleMessageRefresh() {
934 rebuildLayerStacks();
936 doDebugFlashRegions();
941 void SurfaceFlinger::doDebugFlashRegions()
943 // is debugging enabled
944 if (CC_LIKELY(!mDebugRegion))
947 const bool repaintEverything = mRepaintEverything;
948 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
949 const sp<DisplayDevice>& hw(mDisplays[dpy]);
950 if (hw->isDisplayOn()) {
951 // transform the dirty region into this screen's coordinate space
952 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
953 if (!dirtyRegion.isEmpty()) {
954 // redraw the whole screen
955 doComposeSurfaces(hw, Region(hw->bounds()));
957 // and draw the dirty region
958 const int32_t height = hw->getHeight();
959 RenderEngine& engine(getRenderEngine());
960 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
962 hw->compositionComplete();
963 hw->swapBuffers(getHwComposer());
970 if (mDebugRegion > 1) {
971 usleep(mDebugRegion * 1000);
974 HWComposer& hwc(getHwComposer());
975 if (hwc.initCheck() == NO_ERROR) {
976 status_t err = hwc.prepare();
977 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
981 void SurfaceFlinger::preComposition()
983 bool needExtraInvalidate = false;
984 const LayerVector& layers(mDrawingState.layersSortedByZ);
985 const size_t count = layers.size();
986 for (size_t i=0 ; i<count ; i++) {
987 if (layers[i]->onPreComposition()) {
988 needExtraInvalidate = true;
991 if (needExtraInvalidate) {
996 void SurfaceFlinger::postComposition()
998 const LayerVector& layers(mDrawingState.layersSortedByZ);
999 const size_t count = layers.size();
1000 for (size_t i=0 ; i<count ; i++) {
1001 layers[i]->onPostComposition();
1004 const HWComposer& hwc = getHwComposer();
1005 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1007 if (presentFence->isValid()) {
1008 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1009 enableHardwareVsync();
1011 disableHardwareVsync(false);
1015 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1016 if (kIgnorePresentFences) {
1017 if (hw->isDisplayOn()) {
1018 enableHardwareVsync();
1022 if (mAnimCompositionPending) {
1023 mAnimCompositionPending = false;
1025 if (presentFence->isValid()) {
1026 mAnimFrameTracker.setActualPresentFence(presentFence);
1028 // The HWC doesn't support present fences, so use the refresh
1029 // timestamp instead.
1030 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1031 mAnimFrameTracker.setActualPresentTime(presentTime);
1033 mAnimFrameTracker.advanceFrame();
1036 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1040 nsecs_t currentTime = systemTime();
1041 if (mHasPoweredOff) {
1042 mHasPoweredOff = false;
1044 nsecs_t period = mPrimaryDispSync.getPeriod();
1045 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1046 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1047 if (numPeriods < NUM_BUCKETS - 1) {
1048 mFrameBuckets[numPeriods] += elapsedTime;
1050 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1052 mTotalTime += elapsedTime;
1054 mLastSwapTime = currentTime;
1057 void SurfaceFlinger::rebuildLayerStacks() {
1058 updateExtendedMode();
1059 // rebuild the visible layer list per screen
1060 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1062 mVisibleRegionsDirty = false;
1063 invalidateHwcGeometry();
1065 const LayerVector& layers(mDrawingState.layersSortedByZ);
1066 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1067 Region opaqueRegion;
1069 Vector< sp<Layer> > layersSortedByZ;
1070 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1071 const Transform& tr(hw->getTransform());
1072 const Rect bounds(hw->getBounds());
1073 if (hw->isDisplayOn()) {
1074 computeVisibleRegions(hw->getHwcDisplayId(), layers,
1075 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1077 const size_t count = layers.size();
1078 for (size_t i=0 ; i<count ; i++) {
1079 const sp<Layer>& layer(layers[i]);
1081 Region drawRegion(tr.transform(
1082 layer->visibleNonTransparentRegion));
1083 drawRegion.andSelf(bounds);
1084 if (!drawRegion.isEmpty()) {
1085 layersSortedByZ.add(layer);
1090 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1091 hw->undefinedRegion.set(bounds);
1092 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1093 hw->dirtyRegion.orSelf(dirtyRegion);
1098 void SurfaceFlinger::setUpHWComposer() {
1099 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1100 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1101 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1102 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1104 // If nothing has changed (!dirty), don't recompose.
1105 // If something changed, but we don't currently have any visible layers,
1106 // and didn't when we last did a composition, then skip it this time.
1107 // The second rule does two things:
1108 // - When all layers are removed from a display, we'll emit one black
1109 // frame, then nothing more until we get new layers.
1110 // - When a display is created with a private layer stack, we won't
1111 // emit any black frames until a layer is added to the layer stack.
1112 bool mustRecompose = dirty && !(empty && wasEmpty);
1114 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1115 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1116 mustRecompose ? "doing" : "skipping",
1119 wasEmpty ? "+" : "-");
1121 mDisplays[dpy]->beginFrame(mustRecompose);
1123 if (mustRecompose) {
1124 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1128 HWComposer& hwc(getHwComposer());
1129 if (hwc.initCheck() == NO_ERROR) {
1130 // build the h/w work list
1131 if (CC_UNLIKELY(mHwWorkListDirty)) {
1132 mHwWorkListDirty = false;
1133 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1134 sp<const DisplayDevice> hw(mDisplays[dpy]);
1135 const int32_t id = hw->getHwcDisplayId();
1137 const Vector< sp<Layer> >& currentLayers(
1138 hw->getVisibleLayersSortedByZ());
1139 const size_t count = currentLayers.size();
1140 if (hwc.createWorkList(id, count) == NO_ERROR) {
1141 HWComposer::LayerListIterator cur = hwc.begin(id);
1142 const HWComposer::LayerListIterator end = hwc.end(id);
1143 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1144 const sp<Layer>& layer(currentLayers[i]);
1145 layer->setGeometry(hw, *cur);
1146 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1155 // set the per-frame data
1156 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1157 sp<const DisplayDevice> hw(mDisplays[dpy]);
1158 const int32_t id = hw->getHwcDisplayId();
1160 bool freezeSurfacePresent = false;
1161 isfreezeSurfacePresent(freezeSurfacePresent, hw, id);
1162 const Vector< sp<Layer> >& currentLayers(
1163 hw->getVisibleLayersSortedByZ());
1164 const size_t count = currentLayers.size();
1165 HWComposer::LayerListIterator cur = hwc.begin(id);
1166 const HWComposer::LayerListIterator end = hwc.end(id);
1167 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1169 * update the per-frame h/w composer data for each layer
1170 * and build the transparent region of the FB
1172 const sp<Layer>& layer(currentLayers[i]);
1173 layer->setPerFrameData(hw, *cur);
1174 setOrientationEventControl(freezeSurfacePresent,id);
1179 // If possible, attempt to use the cursor overlay on each display.
1180 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1181 sp<const DisplayDevice> hw(mDisplays[dpy]);
1182 const int32_t id = hw->getHwcDisplayId();
1184 const Vector< sp<Layer> >& currentLayers(
1185 hw->getVisibleLayersSortedByZ());
1186 const size_t count = currentLayers.size();
1187 HWComposer::LayerListIterator cur = hwc.begin(id);
1188 const HWComposer::LayerListIterator end = hwc.end(id);
1189 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1190 const sp<Layer>& layer(currentLayers[i]);
1191 if (layer->isPotentialCursor()) {
1192 cur->setIsCursorLayerHint();
1199 status_t err = hwc.prepare();
1200 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1202 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1203 sp<const DisplayDevice> hw(mDisplays[dpy]);
1204 hw->prepareFrame(hwc);
1209 void SurfaceFlinger::doComposition() {
1211 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1212 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1213 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1214 if (hw->isDisplayOn()) {
1215 // transform the dirty region into this screen's coordinate space
1216 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1218 // repaint the framebuffer (if needed)
1219 doDisplayComposition(hw, dirtyRegion);
1221 hw->dirtyRegion.clear();
1222 hw->flip(hw->swapRegion);
1223 hw->swapRegion.clear();
1225 // inform the h/w that we're done compositing
1226 hw->compositionComplete();
1231 void SurfaceFlinger::postFramebuffer()
1235 const nsecs_t now = systemTime();
1236 mDebugInSwapBuffers = now;
1238 HWComposer& hwc(getHwComposer());
1239 if (hwc.initCheck() == NO_ERROR) {
1240 if (!hwc.supportsFramebufferTarget()) {
1242 // "surface must be bound to the calling thread's current context,
1243 // for the current rendering API."
1244 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1249 // make the default display current because the VirtualDisplayDevice code cannot
1250 // deal with dequeueBuffer() being called outside of the composition loop; however
1251 // the code below can call glFlush() which is allowed (and does in some case) call
1253 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1255 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1256 sp<const DisplayDevice> hw(mDisplays[dpy]);
1257 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1258 hw->onSwapBuffersCompleted(hwc);
1259 const size_t count = currentLayers.size();
1260 int32_t id = hw->getHwcDisplayId();
1261 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1262 HWComposer::LayerListIterator cur = hwc.begin(id);
1263 const HWComposer::LayerListIterator end = hwc.end(id);
1264 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1265 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1268 for (size_t i = 0; i < count; i++) {
1269 currentLayers[i]->onLayerDisplayed(hw, NULL);
1274 mLastSwapBufferTime = systemTime() - now;
1275 mDebugInSwapBuffers = 0;
1277 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1278 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1283 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1287 // here we keep a copy of the drawing state (that is the state that's
1288 // going to be overwritten by handleTransactionLocked()) outside of
1289 // mStateLock so that the side-effects of the State assignment
1290 // don't happen with mStateLock held (which can cause deadlocks).
1291 State drawingState(mDrawingState);
1293 Mutex::Autolock _l(mStateLock);
1294 const nsecs_t now = systemTime();
1295 mDebugInTransaction = now;
1297 // Here we're guaranteed that some transaction flags are set
1298 // so we can call handleTransactionLocked() unconditionally.
1299 // We call getTransactionFlags(), which will also clear the flags,
1300 // with mStateLock held to guarantee that mCurrentState won't change
1301 // until the transaction is committed.
1303 transactionFlags = getTransactionFlags(eTransactionMask);
1304 handleTransactionLocked(transactionFlags);
1306 mLastTransactionTime = systemTime() - now;
1307 mDebugInTransaction = 0;
1308 invalidateHwcGeometry();
1309 // here the transaction has been committed
1312 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1314 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1315 const size_t count = currentLayers.size();
1318 * Traversal of the children
1319 * (perform the transaction for each of them if needed)
1322 if (transactionFlags & eTraversalNeeded) {
1323 for (size_t i=0 ; i<count ; i++) {
1324 const sp<Layer>& layer(currentLayers[i]);
1325 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1326 if (!trFlags) continue;
1328 const uint32_t flags = layer->doTransaction(0);
1329 if (flags & Layer::eVisibleRegion)
1330 mVisibleRegionsDirty = true;
1335 * Perform display own transactions if needed
1338 if (transactionFlags & eDisplayTransactionNeeded) {
1339 // here we take advantage of Vector's copy-on-write semantics to
1340 // improve performance by skipping the transaction entirely when
1341 // know that the lists are identical
1342 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1343 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1344 if (!curr.isIdenticalTo(draw)) {
1345 mVisibleRegionsDirty = true;
1346 const size_t cc = curr.size();
1347 size_t dc = draw.size();
1349 // find the displays that were removed
1350 // (ie: in drawing state but not in current state)
1351 // also handle displays that changed
1352 // (ie: displays that are in both lists)
1353 for (size_t i=0 ; i<dc ; i++) {
1354 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1356 // in drawing state but not in current state
1357 if (!draw[i].isMainDisplay()) {
1358 // Call makeCurrent() on the primary display so we can
1359 // be sure that nothing associated with this display
1361 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1362 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1363 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1365 hw->disconnect(getHwComposer());
1366 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1367 mEventThread->onHotplugReceived(draw[i].type, false);
1368 mDisplays.removeItem(draw.keyAt(i));
1370 ALOGW("trying to remove the main display");
1373 // this display is in both lists. see if something changed.
1374 const DisplayDeviceState& state(curr[j]);
1375 const wp<IBinder>& display(curr.keyAt(j));
1376 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1377 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1378 if (state_binder != draw_binder) {
1379 // changing the surface is like destroying and
1380 // recreating the DisplayDevice, so we just remove it
1381 // from the drawing state, so that it get re-added
1383 sp<DisplayDevice> hw(getDisplayDevice(display));
1385 hw->disconnect(getHwComposer());
1386 mDisplays.removeItem(display);
1387 mDrawingState.displays.removeItemsAt(i);
1389 // at this point we must loop to the next item
1393 const sp<DisplayDevice> disp(getDisplayDevice(display));
1395 if (state.layerStack != draw[i].layerStack) {
1396 disp->setLayerStack(state.layerStack);
1398 if ((state.orientation != draw[i].orientation)
1399 || (state.viewport != draw[i].viewport)
1400 || (state.frame != draw[i].frame))
1402 disp->setProjection(state.orientation,
1403 state.viewport, state.frame);
1405 if (state.width != draw[i].width || state.height != draw[i].height) {
1406 disp->setDisplaySize(state.width, state.height);
1412 // find displays that were added
1413 // (ie: in current state but not in drawing state)
1414 for (size_t i=0 ; i<cc ; i++) {
1415 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1416 const DisplayDeviceState& state(curr[i]);
1418 sp<DisplaySurface> dispSurface;
1419 sp<IGraphicBufferProducer> producer;
1420 sp<IGraphicBufferProducer> bqProducer;
1421 sp<IGraphicBufferConsumer> bqConsumer;
1422 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1423 new GraphicBufferAlloc());
1425 int32_t hwcDisplayId = -1;
1426 if (state.isVirtualDisplay()) {
1427 // Virtual displays without a surface are dormant:
1428 // they have external state (layer stack, projection,
1429 // etc.) but no internal state (i.e. a DisplayDevice).
1430 if (state.surface != NULL) {
1433 int status = state.surface->query(
1434 NATIVE_WINDOW_WIDTH, &width);
1435 ALOGE_IF(status != NO_ERROR,
1436 "Unable to query width (%d)", status);
1438 status = state.surface->query(
1439 NATIVE_WINDOW_HEIGHT, &height);
1440 ALOGE_IF(status != NO_ERROR,
1441 "Unable to query height (%d)", status);
1442 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1443 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1444 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1445 hwcDisplayId = allocateHwcDisplayId(state.type);
1448 DisplayUtils::getInstance()->initVDSInstance(mHwc, hwcDisplayId,
1449 state.surface, dispSurface, producer, bqProducer, bqConsumer,
1450 state.displayName, state.isSecure, state.type);
1454 ALOGE_IF(state.surface!=NULL,
1455 "adding a supported display, but rendering "
1456 "surface is provided (%p), ignoring it",
1457 state.surface.get());
1458 hwcDisplayId = allocateHwcDisplayId(state.type);
1459 // for supported (by hwc) displays we provide our
1460 // own rendering surface
1461 dispSurface = new FramebufferSurface(*mHwc, state.type,
1463 producer = bqProducer;
1466 const wp<IBinder>& display(curr.keyAt(i));
1467 if (dispSurface != NULL && producer != NULL) {
1468 sp<DisplayDevice> hw = new DisplayDevice(this,
1469 state.type, hwcDisplayId,
1470 mHwc->getFormat(hwcDisplayId), state.isSecure,
1471 display, dispSurface, producer,
1472 mRenderEngine->getEGLConfig());
1473 hw->setLayerStack(state.layerStack);
1474 hw->setProjection(state.orientation,
1475 state.viewport, state.frame);
1476 hw->setDisplayName(state.displayName);
1477 // When a new display device is added update the active
1478 // config by querying HWC otherwise the default config
1479 // (config 0) will be used.
1480 if (hwcDisplayId >= DisplayDevice::DISPLAY_PRIMARY &&
1481 hwcDisplayId < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1482 int activeConfig = mHwc->getActiveConfig(hwcDisplayId);
1483 if (activeConfig >= 0) {
1484 hw->setActiveConfig(activeConfig);
1487 mDisplays.add(display, hw);
1488 if (state.isVirtualDisplay()) {
1489 if (hwcDisplayId >= 0) {
1490 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1491 hw->getWidth(), hw->getHeight(),
1495 mEventThread->onHotplugReceived(state.type, true);
1503 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1504 // The transform hint might have changed for some layers
1505 // (either because a display has changed, or because a layer
1508 // Walk through all the layers in currentLayers,
1509 // and update their transform hint.
1511 // If a layer is visible only on a single display, then that
1512 // display is used to calculate the hint, otherwise we use the
1515 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1516 // the hint is set before we acquire a buffer from the surface texture.
1518 // NOTE: layer transactions have taken place already, so we use their
1519 // drawing state. However, SurfaceFlinger's own transaction has not
1520 // happened yet, so we must use the current state layer list
1521 // (soon to become the drawing state list).
1523 sp<const DisplayDevice> disp;
1524 uint32_t currentlayerStack = 0;
1525 for (size_t i=0; i<count; i++) {
1526 // NOTE: we rely on the fact that layers are sorted by
1527 // layerStack first (so we don't have to traverse the list
1528 // of displays for every layer).
1529 const sp<Layer>& layer(currentLayers[i]);
1530 uint32_t layerStack = layer->getDrawingState().layerStack;
1531 if (i==0 || currentlayerStack != layerStack) {
1532 currentlayerStack = layerStack;
1533 // figure out if this layerstack is mirrored
1534 // (more than one display) if so, pick the default display,
1535 // if not, pick the only display it's on.
1537 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1538 sp<const DisplayDevice> hw(mDisplays[dpy]);
1539 if (hw->getLayerStack() == currentlayerStack) {
1550 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1551 // redraw after transform hint changes. See bug 8508397.
1553 // could be null when this layer is using a layerStack
1554 // that is not visible on any display. Also can occur at
1555 // screen off/on times.
1556 disp = getDefaultDisplayDevice();
1558 layer->updateTransformHint(disp);
1564 * Perform our own transaction if needed
1567 const LayerVector& layers(mDrawingState.layersSortedByZ);
1568 if (currentLayers.size() > layers.size()) {
1569 // layers have been added
1570 mVisibleRegionsDirty = true;
1573 // some layers might have been removed, so
1574 // we need to update the regions they're exposing.
1575 if (mLayersRemoved) {
1576 mLayersRemoved = false;
1577 mVisibleRegionsDirty = true;
1578 const size_t count = layers.size();
1579 for (size_t i=0 ; i<count ; i++) {
1580 const sp<Layer>& layer(layers[i]);
1581 if (currentLayers.indexOf(layer) < 0) {
1582 // this layer is not visible anymore
1583 // TODO: we could traverse the tree from front to back and
1584 // compute the actual visible region
1585 // TODO: we could cache the transformed region
1586 const Layer::State& s(layer->getDrawingState());
1587 Region visibleReg = s.transform.transform(
1588 Region(Rect(s.active.w, s.active.h)));
1589 invalidateLayerStack(s.layerStack, visibleReg);
1594 commitTransaction();
1596 updateCursorAsync();
1599 void SurfaceFlinger::updateCursorAsync()
1601 HWComposer& hwc(getHwComposer());
1602 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1603 sp<const DisplayDevice> hw(mDisplays[dpy]);
1604 const int32_t id = hw->getHwcDisplayId();
1608 const Vector< sp<Layer> >& currentLayers(
1609 hw->getVisibleLayersSortedByZ());
1610 const size_t count = currentLayers.size();
1611 HWComposer::LayerListIterator cur = hwc.begin(id);
1612 const HWComposer::LayerListIterator end = hwc.end(id);
1613 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1614 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1617 const sp<Layer>& layer(currentLayers[i]);
1618 Rect cursorPos = layer->getPosition(hw);
1619 hwc.setCursorPositionAsync(id, cursorPos);
1625 void SurfaceFlinger::commitTransaction()
1627 if (!mLayersPendingRemoval.isEmpty()) {
1628 // Notify removed layers now that they can't be drawn from
1629 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1630 mLayersPendingRemoval[i]->onRemoved();
1632 mLayersPendingRemoval.clear();
1635 // If this transaction is part of a window animation then the next frame
1636 // we composite should be considered an animation as well.
1637 mAnimCompositionPending = mAnimTransactionPending;
1639 mDrawingState = mCurrentState;
1640 mTransactionPending = false;
1641 mAnimTransactionPending = false;
1642 mTransactionCV.broadcast();
1645 void SurfaceFlinger::computeVisibleRegions(size_t dpy,
1646 const LayerVector& currentLayers, uint32_t layerStack,
1647 Region& outDirtyRegion, Region& outOpaqueRegion)
1651 Region aboveOpaqueLayers;
1652 Region aboveCoveredLayers;
1655 outDirtyRegion.clear();
1656 bool bIgnoreLayers = false;
1658 getIndexLOI(dpy, currentLayers, bIgnoreLayers, indexLOI);
1660 size_t i = currentLayers.size();
1662 const sp<Layer>& layer = currentLayers[i];
1664 // start with the whole surface at its current location
1665 const Layer::State& s(layer->getDrawingState());
1667 if(updateLayerVisibleNonTransparentRegion(dpy, layer,
1668 bIgnoreLayers, indexLOI,
1673 * opaqueRegion: area of a surface that is fully opaque.
1675 Region opaqueRegion;
1678 * visibleRegion: area of a surface that is visible on screen
1679 * and not fully transparent. This is essentially the layer's
1680 * footprint minus the opaque regions above it.
1681 * Areas covered by a translucent surface are considered visible.
1683 Region visibleRegion;
1686 * coveredRegion: area of a surface that is covered by all
1687 * visible regions above it (which includes the translucent areas).
1689 Region coveredRegion;
1692 * transparentRegion: area of a surface that is hinted to be completely
1693 * transparent. This is only used to tell when the layer has no visible
1694 * non-transparent regions and can be removed from the layer list. It
1695 * does not affect the visibleRegion of this layer or any layers
1696 * beneath it. The hint may not be correct if apps don't respect the
1697 * SurfaceView restrictions (which, sadly, some don't).
1699 Region transparentRegion;
1702 // handle hidden surfaces by setting the visible region to empty
1703 if (CC_LIKELY(layer->isVisible())) {
1704 const bool translucent = !layer->isOpaque(s);
1705 Rect bounds(s.transform.transform(layer->computeBounds()));
1706 visibleRegion.set(bounds);
1707 if (!visibleRegion.isEmpty()) {
1708 // Remove the transparent area from the visible region
1710 const Transform tr(s.transform);
1711 if (tr.transformed()) {
1712 if (tr.preserveRects()) {
1713 // transform the transparent region
1714 transparentRegion = tr.transform(s.activeTransparentRegion);
1716 // transformation too complex, can't do the
1717 // transparent region optimization.
1718 transparentRegion.clear();
1721 transparentRegion = s.activeTransparentRegion;
1725 // compute the opaque region
1726 const int32_t layerOrientation = s.transform.getOrientation();
1727 if (s.alpha==255 && !translucent &&
1728 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1729 // the opaque region is the layer's footprint
1730 opaqueRegion = visibleRegion;
1735 // Clip the covered region to the visible region
1736 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1738 // Update aboveCoveredLayers for next (lower) layer
1739 aboveCoveredLayers.orSelf(visibleRegion);
1741 // subtract the opaque region covered by the layers above us
1742 visibleRegion.subtractSelf(aboveOpaqueLayers);
1744 // compute this layer's dirty region
1745 if (layer->contentDirty) {
1746 // we need to invalidate the whole region
1747 dirty = visibleRegion;
1748 // as well, as the old visible region
1749 dirty.orSelf(layer->visibleRegion);
1750 layer->contentDirty = false;
1752 /* compute the exposed region:
1753 * the exposed region consists of two components:
1754 * 1) what's VISIBLE now and was COVERED before
1755 * 2) what's EXPOSED now less what was EXPOSED before
1757 * note that (1) is conservative, we start with the whole
1758 * visible region but only keep what used to be covered by
1759 * something -- which mean it may have been exposed.
1761 * (2) handles areas that were not covered by anything but got
1762 * exposed because of a resize.
1764 const Region newExposed = visibleRegion - coveredRegion;
1765 const Region oldVisibleRegion = layer->visibleRegion;
1766 const Region oldCoveredRegion = layer->coveredRegion;
1767 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1768 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1770 dirty.subtractSelf(aboveOpaqueLayers);
1772 // accumulate to the screen dirty region
1773 outDirtyRegion.orSelf(dirty);
1775 // Update aboveOpaqueLayers for next (lower) layer
1776 aboveOpaqueLayers.orSelf(opaqueRegion);
1778 // Store the visible region in screen space
1779 layer->setVisibleRegion(visibleRegion);
1780 layer->setCoveredRegion(coveredRegion);
1781 layer->setVisibleNonTransparentRegion(
1782 visibleRegion.subtract(transparentRegion));
1785 outOpaqueRegion = aboveOpaqueLayers;
1788 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1789 const Region& dirty) {
1790 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1791 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1792 if (hw->getLayerStack() == layerStack) {
1793 hw->dirtyRegion.orSelf(dirty);
1798 bool SurfaceFlinger::handlePageFlip()
1802 bool visibleRegions = false;
1803 const LayerVector& layers(mDrawingState.layersSortedByZ);
1804 bool frameQueued = false;
1806 // Store the set of layers that need updates. This set must not change as
1807 // buffers are being latched, as this could result in a deadlock.
1808 // Example: Two producers share the same command stream and:
1809 // 1.) Layer 0 is latched
1810 // 2.) Layer 0 gets a new frame
1811 // 2.) Layer 1 gets a new frame
1812 // 3.) Layer 1 is latched.
1813 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1814 // second frame. But layer 0's second frame could be waiting on display.
1815 Vector<Layer*> layersWithQueuedFrames;
1816 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1817 const sp<Layer>& layer(layers[i]);
1818 if (layer->hasQueuedFrame()) {
1820 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1821 layersWithQueuedFrames.push_back(layer.get());
1823 layer->useEmptyDamage();
1826 layer->useEmptyDamage();
1829 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1830 Layer* layer = layersWithQueuedFrames[i];
1831 const Region dirty(layer->latchBuffer(visibleRegions));
1832 layer->useSurfaceDamage();
1833 const Layer::State& s(layer->getDrawingState());
1834 invalidateLayerStack(s.layerStack, dirty);
1837 mVisibleRegionsDirty |= visibleRegions;
1839 // If we will need to wake up at some time in the future to deal with a
1840 // queued frame that shouldn't be displayed during this vsync period, wake
1841 // up during the next vsync period to check again.
1842 if (frameQueued && layersWithQueuedFrames.empty()) {
1843 signalLayerUpdate();
1846 // Only continue with the refresh if there is actually new work to do
1847 return !layersWithQueuedFrames.empty();
1850 void SurfaceFlinger::invalidateHwcGeometry()
1852 mHwWorkListDirty = true;
1856 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1857 const Region& inDirtyRegion)
1859 // We only need to actually compose the display if:
1860 // 1) It is being handled by hardware composer, which may need this to
1861 // keep its virtual display state machine in sync, or
1862 // 2) There is work to be done (the dirty region isn't empty)
1863 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1864 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1868 Region dirtyRegion(inDirtyRegion);
1870 // compute the invalid region
1871 hw->swapRegion.orSelf(dirtyRegion);
1873 uint32_t flags = hw->getFlags();
1874 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1875 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1876 // takes a rectangle, we must make sure to update that whole
1877 // rectangle in that case
1878 dirtyRegion.set(hw->swapRegion.bounds());
1880 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1881 // We need to redraw the rectangle that will be updated
1882 // (pushed to the framebuffer).
1883 // This is needed because PARTIAL_UPDATES only takes one
1884 // rectangle instead of a region (see DisplayDevice::flip())
1885 dirtyRegion.set(hw->swapRegion.bounds());
1887 // we need to redraw everything (the whole screen)
1888 dirtyRegion.set(hw->bounds());
1889 hw->swapRegion = dirtyRegion;
1893 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1894 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1896 RenderEngine& engine(getRenderEngine());
1897 mat4 colorMatrix = mColorMatrix;
1899 colorMatrix = colorMatrix * mDaltonizer();
1901 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1902 doComposeSurfaces(hw, dirtyRegion);
1903 engine.setupColorTransform(oldMatrix);
1906 // update the swap region and clear the dirty region
1907 hw->swapRegion.orSelf(dirtyRegion);
1909 // swap buffers (presentation)
1910 hw->swapBuffers(getHwComposer());
1913 bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1915 RenderEngine& engine(getRenderEngine());
1916 const int32_t id = hw->getHwcDisplayId();
1917 HWComposer& hwc(getHwComposer());
1918 HWComposer::LayerListIterator cur = hwc.begin(id);
1919 const HWComposer::LayerListIterator end = hwc.end(id);
1921 bool hasGlesComposition = hwc.hasGlesComposition(id);
1922 if (hasGlesComposition) {
1923 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1924 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1925 hw->getDisplayName().string());
1926 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1927 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1928 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1933 // Never touch the framebuffer if we don't have any framebuffer layers
1934 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1935 if (hasHwcComposition) {
1936 // when using overlays, we assume a fully transparent framebuffer
1937 // NOTE: we could reduce how much we need to clear, for instance
1938 // remove where there are opaque FB layers. however, on some
1939 // GPUs doing a "clean slate" clear might be more efficient.
1940 // We'll revisit later if needed.
1941 engine.clearWithColor(0, 0, 0, 0);
1943 // we start with the whole screen area
1944 const Region bounds(hw->getBounds());
1946 // we remove the scissor part
1947 // we're left with the letterbox region
1948 // (common case is that letterbox ends-up being empty)
1949 const Region letterbox(bounds.subtract(hw->getScissor()));
1951 // compute the area to clear
1952 Region region(hw->undefinedRegion.merge(letterbox));
1954 // but limit it to the dirty region
1955 region.andSelf(dirty);
1957 // screen is already cleared here
1958 if (!region.isEmpty()) {
1959 // can happen with SurfaceView
1960 drawWormhole(hw, region);
1964 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1965 // just to be on the safe side, we don't set the
1966 // scissor on the main display. It should never be needed
1967 // anyways (though in theory it could since the API allows it).
1968 const Rect& bounds(hw->getBounds());
1969 const Rect& scissor(hw->getScissor());
1970 if (scissor != bounds) {
1971 // scissor doesn't match the screen's dimensions, so we
1972 // need to clear everything outside of it and enable
1973 // the GL scissor so we don't draw anything where we shouldn't
1975 // enable scissor for this frame
1976 const uint32_t height = hw->getHeight();
1977 engine.setScissor(scissor.left, height - scissor.bottom,
1978 scissor.getWidth(), scissor.getHeight());
1984 * and then, render the layers targeted at the framebuffer
1987 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1988 const size_t count = layers.size();
1989 const Transform& tr = hw->getTransform();
1991 // we're using h/w composer
1992 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1993 const sp<Layer>& layer(layers[i]);
1994 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1995 if (!clip.isEmpty()) {
1996 switch (cur->getCompositionType()) {
1997 case HWC_CURSOR_OVERLAY:
1999 const Layer::State& state(layer->getDrawingState());
2000 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2002 && layer->isOpaque(state) && (state.alpha == 0xFF)
2003 && hasGlesComposition) {
2004 // never clear the very first layer since we're
2005 // guaranteed the FB is already cleared
2006 layer->clearWithOpenGL(hw, clip);
2010 case HWC_FRAMEBUFFER: {
2011 layer->draw(hw, clip);
2014 case HWC_FRAMEBUFFER_TARGET: {
2015 // this should not happen as the iterator shouldn't
2016 // let us get there.
2017 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2022 layer->setAcquireFence(hw, *cur);
2025 // we're not using h/w composer
2026 for (size_t i=0 ; i<count ; ++i) {
2027 const sp<Layer>& layer(layers[i]);
2028 const Region clip(dirty.intersect(
2029 tr.transform(layer->visibleRegion)));
2030 if (!clip.isEmpty()) {
2031 layer->draw(hw, clip);
2036 // disable scissor at the end of the frame
2037 engine.disableScissor();
2041 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2042 const int32_t height = hw->getHeight();
2043 RenderEngine& engine(getRenderEngine());
2044 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2047 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2048 const sp<IBinder>& handle,
2049 const sp<IGraphicBufferProducer>& gbc,
2050 const sp<Layer>& lbc)
2052 // add this layer to the current state list
2054 Mutex::Autolock _l(mStateLock);
2055 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2058 mCurrentState.layersSortedByZ.add(lbc);
2059 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2062 // attach this layer to the client
2063 client->attachLayer(handle, lbc);
2068 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2069 Mutex::Autolock _l(mStateLock);
2070 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2072 mLayersPendingRemoval.push(layer);
2073 mLayersRemoved = true;
2074 setTransactionFlags(eTransactionNeeded);
2077 return status_t(index);
2080 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2081 return android_atomic_release_load(&mTransactionFlags);
2084 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2085 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2088 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2089 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2090 if ((old & flags)==0) { // wake the server up
2091 signalTransaction();
2096 void SurfaceFlinger::setTransactionState(
2097 const Vector<ComposerState>& state,
2098 const Vector<DisplayState>& displays,
2103 delayDPTransactionIfNeeded(displays);
2104 Mutex::Autolock _l(mStateLock);
2105 uint32_t transactionFlags = 0;
2107 if (flags & eAnimation) {
2108 // For window updates that are part of an animation we must wait for
2109 // previous animation "frames" to be handled.
2110 while (mAnimTransactionPending) {
2111 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2112 if (CC_UNLIKELY(err != NO_ERROR)) {
2113 // just in case something goes wrong in SF, return to the
2114 // caller after a few seconds.
2115 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2116 "waiting for previous animation frame");
2117 mAnimTransactionPending = false;
2123 size_t count = displays.size();
2124 for (size_t i=0 ; i<count ; i++) {
2125 const DisplayState& s(displays[i]);
2126 transactionFlags |= setDisplayStateLocked(s);
2129 count = state.size();
2130 for (size_t i=0 ; i<count ; i++) {
2131 const ComposerState& s(state[i]);
2132 // Here we need to check that the interface we're given is indeed
2133 // one of our own. A malicious client could give us a NULL
2134 // IInterface, or one of its own or even one of our own but a
2135 // different type. All these situations would cause us to crash.
2137 // NOTE: it would be better to use RTTI as we could directly check
2138 // that we have a Client*. however, RTTI is disabled in Android.
2139 if (s.client != NULL) {
2140 sp<IBinder> binder = IInterface::asBinder(s.client);
2141 if (binder != NULL) {
2142 String16 desc(binder->getInterfaceDescriptor());
2143 if (desc == ISurfaceComposerClient::descriptor) {
2144 sp<Client> client( static_cast<Client *>(s.client.get()) );
2145 transactionFlags |= setClientStateLocked(client, s.state);
2151 if (transactionFlags) {
2152 // this triggers the transaction
2153 setTransactionFlags(transactionFlags);
2155 // if this is a synchronous transaction, wait for it to take effect
2156 // before returning.
2157 if (flags & eSynchronous) {
2158 mTransactionPending = true;
2160 if (flags & eAnimation) {
2161 mAnimTransactionPending = true;
2163 while (mTransactionPending) {
2164 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2165 if (CC_UNLIKELY(err != NO_ERROR)) {
2166 // just in case something goes wrong in SF, return to the
2167 // called after a few seconds.
2168 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2169 mTransactionPending = false;
2176 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2178 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2183 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2184 if (disp.isValid()) {
2185 const uint32_t what = s.what;
2186 if (what & DisplayState::eSurfaceChanged) {
2187 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2188 disp.surface = s.surface;
2189 flags |= eDisplayTransactionNeeded;
2192 if (what & DisplayState::eLayerStackChanged) {
2193 if (disp.layerStack != s.layerStack) {
2194 disp.layerStack = s.layerStack;
2195 flags |= eDisplayTransactionNeeded;
2198 if (what & DisplayState::eDisplayProjectionChanged) {
2199 if (disp.orientation != s.orientation) {
2200 disp.orientation = s.orientation;
2201 flags |= eDisplayTransactionNeeded;
2203 if (disp.frame != s.frame) {
2204 disp.frame = s.frame;
2205 flags |= eDisplayTransactionNeeded;
2207 if (disp.viewport != s.viewport) {
2208 disp.viewport = s.viewport;
2209 flags |= eDisplayTransactionNeeded;
2212 if (what & DisplayState::eDisplaySizeChanged) {
2213 if (disp.width != s.width) {
2214 disp.width = s.width;
2215 flags |= eDisplayTransactionNeeded;
2217 if (disp.height != s.height) {
2218 disp.height = s.height;
2219 flags |= eDisplayTransactionNeeded;
2226 uint32_t SurfaceFlinger::setClientStateLocked(
2227 const sp<Client>& client,
2228 const layer_state_t& s)
2231 sp<Layer> layer(client->getLayerUser(s.surface));
2233 const uint32_t what = s.what;
2234 if (what & layer_state_t::ePositionChanged) {
2235 if (layer->setPosition(s.x, s.y))
2236 flags |= eTraversalNeeded;
2238 if (what & layer_state_t::eLayerChanged) {
2239 // NOTE: index needs to be calculated before we update the state
2240 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2241 if (layer->setLayer(s.z)) {
2242 mCurrentState.layersSortedByZ.removeAt(idx);
2243 mCurrentState.layersSortedByZ.add(layer);
2244 // we need traversal (state changed)
2245 // AND transaction (list changed)
2246 flags |= eTransactionNeeded|eTraversalNeeded;
2249 if (what & layer_state_t::eSizeChanged) {
2250 if (layer->setSize(s.w, s.h)) {
2251 flags |= eTraversalNeeded;
2254 if (what & layer_state_t::eAlphaChanged) {
2255 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2256 flags |= eTraversalNeeded;
2258 if (what & layer_state_t::eMatrixChanged) {
2259 if (layer->setMatrix(s.matrix))
2260 flags |= eTraversalNeeded;
2262 if (what & layer_state_t::eTransparentRegionChanged) {
2263 if (layer->setTransparentRegionHint(s.transparentRegion))
2264 flags |= eTraversalNeeded;
2266 if (what & layer_state_t::eFlagsChanged) {
2267 if (layer->setFlags(s.flags, s.mask))
2268 flags |= eTraversalNeeded;
2270 if (what & layer_state_t::eCropChanged) {
2271 if (layer->setCrop(s.crop))
2272 flags |= eTraversalNeeded;
2274 if (what & layer_state_t::eLayerStackChanged) {
2275 // NOTE: index needs to be calculated before we update the state
2276 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2277 if (layer->setLayerStack(s.layerStack)) {
2278 mCurrentState.layersSortedByZ.removeAt(idx);
2279 mCurrentState.layersSortedByZ.add(layer);
2280 // we need traversal (state changed)
2281 // AND transaction (list changed)
2282 flags |= eTransactionNeeded|eTraversalNeeded;
2289 status_t SurfaceFlinger::createLayer(
2290 const String8& name,
2291 const sp<Client>& client,
2292 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2293 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2295 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2296 if (int32_t(w|h) < 0) {
2297 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2302 status_t result = NO_ERROR;
2306 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2307 case ISurfaceComposerClient::eFXSurfaceNormal:
2308 result = createNormalLayer(client,
2309 name, w, h, flags, format,
2310 handle, gbp, &layer);
2312 case ISurfaceComposerClient::eFXSurfaceDim:
2313 result = createDimLayer(client,
2315 handle, gbp, &layer);
2322 if (result != NO_ERROR) {
2326 result = addClientLayer(client, *handle, *gbp, layer);
2327 if (result != NO_ERROR) {
2331 setTransactionFlags(eTransactionNeeded);
2335 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2336 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2337 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2339 // initialize the surfaces
2341 case PIXEL_FORMAT_TRANSPARENT:
2342 case PIXEL_FORMAT_TRANSLUCENT:
2343 format = PIXEL_FORMAT_RGBA_8888;
2345 case PIXEL_FORMAT_OPAQUE:
2346 format = PIXEL_FORMAT_RGBX_8888;
2350 *outLayer = DisplayUtils::getInstance()->getLayerInstance(this, client, name, w, h, flags);
2351 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2352 if (err == NO_ERROR) {
2353 *handle = (*outLayer)->getHandle();
2354 *gbp = (*outLayer)->getProducer();
2357 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2361 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2362 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2363 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2365 *outLayer = new LayerDim(this, client, name, w, h, flags);
2366 *handle = (*outLayer)->getHandle();
2367 *gbp = (*outLayer)->getProducer();
2371 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2373 // called by the window manager when it wants to remove a Layer
2374 status_t err = NO_ERROR;
2375 sp<Layer> l(client->getLayerUser(handle));
2377 err = removeLayer(l);
2378 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2379 "error removing layer=%p (%s)", l.get(), strerror(-err));
2384 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2386 // called by ~LayerCleaner() when all references to the IBinder (handle)
2388 status_t err = NO_ERROR;
2389 sp<Layer> l(layer.promote());
2391 err = removeLayer(l);
2392 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2393 "error removing layer=%p (%s)", l.get(), strerror(-err));
2398 // ---------------------------------------------------------------------------
2400 void SurfaceFlinger::onInitializeDisplays() {
2401 // reset screen orientation and use primary layer stack
2402 Vector<ComposerState> state;
2403 Vector<DisplayState> displays;
2405 d.what = DisplayState::eDisplayProjectionChanged |
2406 DisplayState::eLayerStackChanged;
2407 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2409 d.orientation = DisplayState::eOrientationDefault;
2410 d.frame.makeInvalid();
2411 d.viewport.makeInvalid();
2415 setTransactionState(state, displays, 0);
2416 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2418 const nsecs_t period =
2419 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2420 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2423 void SurfaceFlinger::initializeDisplays() {
2424 class MessageScreenInitialized : public MessageBase {
2425 SurfaceFlinger* flinger;
2427 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2428 virtual bool handler() {
2429 flinger->onInitializeDisplays();
2433 sp<MessageBase> msg = new MessageScreenInitialized(this);
2434 postMessageAsync(msg); // we may be called from main thread, use async message
2437 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2439 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2441 int32_t type = hw->getDisplayType();
2442 int currentMode = hw->getPowerMode();
2444 if (mode == currentMode) {
2445 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2449 hw->setPowerMode(mode);
2450 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2451 ALOGW("Trying to set power mode for virtual display");
2455 if (currentMode == HWC_POWER_MODE_OFF) {
2456 getHwComposer().setPowerMode(type, mode);
2457 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2458 // FIXME: eventthread only knows about the main display right now
2459 mEventThread->onScreenAcquired();
2460 resyncToHardwareVsync(true);
2463 mVisibleRegionsDirty = true;
2464 mHasPoweredOff = true;
2465 repaintEverything();
2466 } else if (mode == HWC_POWER_MODE_OFF) {
2467 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2468 disableHardwareVsync(true); // also cancels any in-progress resync
2470 // FIXME: eventthread only knows about the main display right now
2471 mEventThread->onScreenReleased();
2474 getHwComposer().setPowerMode(type, mode);
2475 mVisibleRegionsDirty = true;
2476 // from this point on, SF will stop drawing on this display
2478 getHwComposer().setPowerMode(type, mode);
2482 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2483 class MessageSetPowerMode: public MessageBase {
2484 SurfaceFlinger& mFlinger;
2485 sp<IBinder> mDisplay;
2488 MessageSetPowerMode(SurfaceFlinger& flinger,
2489 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2490 mDisplay(disp) { mMode = mode; }
2491 virtual bool handler() {
2492 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2494 ALOGE("Attempt to set power mode = %d for null display %p",
2495 mMode, mDisplay.get());
2496 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2497 ALOGW("Attempt to set power mode = %d for virtual display",
2500 mFlinger.setPowerModeInternal(hw, mMode);
2505 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2506 postMessageSync(msg);
2509 // ---------------------------------------------------------------------------
2511 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2515 IPCThreadState* ipc = IPCThreadState::self();
2516 const int pid = ipc->getCallingPid();
2517 const int uid = ipc->getCallingUid();
2518 if ((uid != AID_SHELL) &&
2519 !PermissionCache::checkPermission(sDump, pid, uid)) {
2520 result.appendFormat("Permission Denial: "
2521 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2523 // Try to get the main lock, but give up after one second
2524 // (this would indicate SF is stuck, but we want to be able to
2525 // print something in dumpsys).
2526 status_t err = mStateLock.timedLock(s2ns(1));
2527 bool locked = (err == NO_ERROR);
2529 result.appendFormat(
2530 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2531 "dumping anyways (no locks held)\n", strerror(-err), err);
2534 bool dumpAll = true;
2536 size_t numArgs = args.size();
2538 if ((index < numArgs) &&
2539 (args[index] == String16("--list"))) {
2541 listLayersLocked(args, index, result);
2545 if ((index < numArgs) &&
2546 (args[index] == String16("--latency"))) {
2548 dumpStatsLocked(args, index, result);
2552 if ((index < numArgs) &&
2553 (args[index] == String16("--latency-clear"))) {
2555 clearStatsLocked(args, index, result);
2559 if ((index < numArgs) &&
2560 (args[index] == String16("--dispsync"))) {
2562 mPrimaryDispSync.dump(result);
2566 if ((index < numArgs) &&
2567 (args[index] == String16("--static-screen"))) {
2569 dumpStaticScreenStats(result);
2575 dumpAllLocked(args, index, result);
2579 mStateLock.unlock();
2582 write(fd, result.string(), result.size());
2586 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2587 size_t& /* index */, String8& result) const
2589 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2590 const size_t count = currentLayers.size();
2591 for (size_t i=0 ; i<count ; i++) {
2592 const sp<Layer>& layer(currentLayers[i]);
2593 result.appendFormat("%s\n", layer->getName().string());
2597 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2598 String8& result) const
2601 if (index < args.size()) {
2602 name = String8(args[index]);
2606 const nsecs_t period =
2607 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2608 result.appendFormat("%" PRId64 "\n", period);
2610 if (name.isEmpty()) {
2611 mAnimFrameTracker.dumpStats(result);
2613 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2614 const size_t count = currentLayers.size();
2615 for (size_t i=0 ; i<count ; i++) {
2616 const sp<Layer>& layer(currentLayers[i]);
2617 if (name == layer->getName()) {
2618 layer->dumpFrameStats(result);
2624 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2625 String8& /* result */)
2628 if (index < args.size()) {
2629 name = String8(args[index]);
2633 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2634 const size_t count = currentLayers.size();
2635 for (size_t i=0 ; i<count ; i++) {
2636 const sp<Layer>& layer(currentLayers[i]);
2637 if (name.isEmpty() || (name == layer->getName())) {
2638 layer->clearFrameStats();
2642 mAnimFrameTracker.clearStats();
2645 // This should only be called from the main thread. Otherwise it would need
2646 // the lock and should use mCurrentState rather than mDrawingState.
2647 void SurfaceFlinger::logFrameStats() {
2648 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2649 const size_t count = drawingLayers.size();
2650 for (size_t i=0 ; i<count ; i++) {
2651 const sp<Layer>& layer(drawingLayers[i]);
2652 layer->logFrameStats();
2655 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2658 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2660 static const char* config =
2662 #ifdef HAS_CONTEXT_PRIORITY
2663 " HAS_CONTEXT_PRIORITY"
2665 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2666 " NEVER_DEFAULT_TO_ASYNC_MODE"
2668 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2669 " TARGET_DISABLE_TRIPLE_BUFFERING"
2672 result.append(config);
2675 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2677 result.appendFormat("Static screen stats:\n");
2678 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2679 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2680 float percent = 100.0f *
2681 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2682 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2683 b + 1, bucketTimeSec, percent);
2685 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2686 float percent = 100.0f *
2687 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2688 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2689 NUM_BUCKETS - 1, bucketTimeSec, percent);
2692 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2693 String8& result) const
2695 bool colorize = false;
2696 if (index < args.size()
2697 && (args[index] == String16("--color"))) {
2702 Colorizer colorizer(colorize);
2704 // figure out if we're stuck somewhere
2705 const nsecs_t now = systemTime();
2706 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2707 const nsecs_t inTransaction(mDebugInTransaction);
2708 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2709 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2712 * Dump library configuration.
2715 colorizer.bold(result);
2716 result.append("Build configuration:");
2717 colorizer.reset(result);
2718 appendSfConfigString(result);
2719 appendUiConfigString(result);
2720 appendGuiConfigString(result);
2721 result.append("\n");
2723 colorizer.bold(result);
2724 result.append("Sync configuration: ");
2725 colorizer.reset(result);
2726 result.append(SyncFeatures::getInstance().toString());
2727 result.append("\n");
2729 colorizer.bold(result);
2730 result.append("DispSync configuration: ");
2731 colorizer.reset(result);
2732 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2733 "present offset %d ns (refresh %" PRId64 " ns)",
2734 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2735 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2736 result.append("\n");
2738 // Dump static screen stats
2739 result.append("\n");
2740 dumpStaticScreenStats(result);
2741 result.append("\n");
2744 * Dump the visible layer list
2746 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2747 const size_t count = currentLayers.size();
2748 colorizer.bold(result);
2749 result.appendFormat("Visible layers (count = %zu)\n", count);
2750 colorizer.reset(result);
2751 for (size_t i=0 ; i<count ; i++) {
2752 const sp<Layer>& layer(currentLayers[i]);
2753 layer->dump(result, colorizer);
2757 * Dump Display state
2760 colorizer.bold(result);
2761 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2762 colorizer.reset(result);
2763 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2764 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2769 * Dump SurfaceFlinger global state
2772 colorizer.bold(result);
2773 result.append("SurfaceFlinger global state:\n");
2774 colorizer.reset(result);
2776 HWComposer& hwc(getHwComposer());
2777 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2779 colorizer.bold(result);
2780 result.appendFormat("EGL implementation : %s\n",
2781 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2782 colorizer.reset(result);
2783 result.appendFormat("%s\n",
2784 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2786 mRenderEngine->dump(result);
2788 hw->undefinedRegion.dump(result, "undefinedRegion");
2789 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2790 hw->getOrientation(), hw->isDisplayOn());
2791 result.appendFormat(
2792 " last eglSwapBuffers() time: %f us\n"
2793 " last transaction time : %f us\n"
2794 " transaction-flags : %08x\n"
2795 " refresh-rate : %f fps\n"
2798 " gpu_to_cpu_unsupported : %d\n"
2800 mLastSwapBufferTime/1000.0,
2801 mLastTransactionTime/1000.0,
2803 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2804 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2805 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2806 !mGpuToCpuSupported);
2808 result.appendFormat(" eglSwapBuffers time: %f us\n",
2809 inSwapBuffersDuration/1000.0);
2811 result.appendFormat(" transaction time: %f us\n",
2812 inTransactionDuration/1000.0);
2817 mEventThread->dump(result);
2820 * Dump HWComposer state
2822 colorizer.bold(result);
2823 result.append("h/w composer state:\n");
2824 colorizer.reset(result);
2825 result.appendFormat(" h/w composer %s and %s\n",
2826 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2827 (mDebugDisableHWC || mDebugRegion || mDaltonize
2828 || mHasColorMatrix) ? "disabled" : "enabled");
2832 * Dump gralloc state
2834 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2838 const Vector< sp<Layer> >&
2839 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2840 // Note: mStateLock is held here
2842 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2843 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2844 dpy = mDisplays.keyAt(i);
2849 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2850 // Just use the primary display so we have something to return
2851 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2853 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2856 bool SurfaceFlinger::startDdmConnection()
2858 void* libddmconnection_dso =
2859 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2860 if (!libddmconnection_dso) {
2863 void (*DdmConnection_start)(const char* name);
2864 DdmConnection_start =
2865 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2866 if (!DdmConnection_start) {
2867 dlclose(libddmconnection_dso);
2870 (*DdmConnection_start)(getServiceName());
2874 status_t SurfaceFlinger::onTransact(
2875 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2878 case CREATE_CONNECTION:
2879 case CREATE_DISPLAY:
2880 case SET_TRANSACTION_STATE:
2882 case CLEAR_ANIMATION_FRAME_STATS:
2883 case GET_ANIMATION_FRAME_STATS:
2884 case SET_POWER_MODE:
2886 // codes that require permission check
2887 IPCThreadState* ipc = IPCThreadState::self();
2888 const int pid = ipc->getCallingPid();
2889 const int uid = ipc->getCallingUid();
2890 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2891 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2892 ALOGE("Permission Denial: "
2893 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2894 return PERMISSION_DENIED;
2898 case CAPTURE_SCREEN:
2900 // codes that require permission check
2901 IPCThreadState* ipc = IPCThreadState::self();
2902 const int pid = ipc->getCallingPid();
2903 const int uid = ipc->getCallingUid();
2904 if ((uid != AID_GRAPHICS) &&
2905 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2906 ALOGE("Permission Denial: "
2907 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2908 return PERMISSION_DENIED;
2914 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2915 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2916 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2917 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2918 IPCThreadState* ipc = IPCThreadState::self();
2919 const int pid = ipc->getCallingPid();
2920 const int uid = ipc->getCallingUid();
2921 ALOGE("Permission Denial: "
2922 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2923 return PERMISSION_DENIED;
2927 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2928 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2930 case 1002: // SHOW_UPDATES
2931 n = data.readInt32();
2932 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2933 invalidateHwcGeometry();
2934 repaintEverything();
2936 case 1004:{ // repaint everything
2937 repaintEverything();
2940 case 1005:{ // force transaction
2941 setTransactionFlags(
2943 eDisplayTransactionNeeded|
2947 case 1006:{ // send empty update
2951 case 1008: // toggle use of hw composer
2952 n = data.readInt32();
2953 mDebugDisableHWC = n ? 1 : 0;
2954 invalidateHwcGeometry();
2955 repaintEverything();
2957 case 1009: // toggle use of transform hint
2958 n = data.readInt32();
2959 mDebugDisableTransformHint = n ? 1 : 0;
2960 invalidateHwcGeometry();
2961 repaintEverything();
2963 case 1010: // interrogate.
2964 reply->writeInt32(0);
2965 reply->writeInt32(0);
2966 reply->writeInt32(mDebugRegion);
2967 reply->writeInt32(0);
2968 reply->writeInt32(mDebugDisableHWC);
2971 Mutex::Autolock _l(mStateLock);
2972 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2973 reply->writeInt32(hw->getPageFlipCount());
2978 n = data.readInt32();
2980 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2981 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2982 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2985 mDaltonizer.setMode(Daltonizer::correction);
2987 mDaltonizer.setMode(Daltonizer::simulation);
2990 invalidateHwcGeometry();
2991 repaintEverything();
2995 // apply a color matrix
2996 n = data.readInt32();
2997 mHasColorMatrix = n ? 1 : 0;
2999 // color matrix is sent as mat3 matrix followed by vec3
3000 // offset, then packed into a mat4 where the last row is
3001 // the offset and extra values are 0
3002 for (size_t i = 0 ; i < 4; i++) {
3003 for (size_t j = 0; j < 4; j++) {
3004 mColorMatrix[i][j] = data.readFloat();
3008 mColorMatrix = mat4();
3010 invalidateHwcGeometry();
3011 repaintEverything();
3014 // This is an experimental interface
3015 // Needs to be shifted to proper binder interface when we productize
3017 n = data.readInt32();
3018 mPrimaryDispSync.setRefreshSkipCount(n);
3022 n = data.readInt32();
3023 mForceFullDamage = static_cast<bool>(n);
3026 case 1018: { // Modify Choreographer's phase offset
3027 n = data.readInt32();
3028 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3031 case 1019: { // Modify SurfaceFlinger's phase offset
3032 n = data.readInt32();
3033 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3041 void SurfaceFlinger::repaintEverything() {
3042 android_atomic_or(1, &mRepaintEverything);
3043 signalTransaction();
3046 // ---------------------------------------------------------------------------
3047 // Capture screen into an IGraphiBufferProducer
3048 // ---------------------------------------------------------------------------
3050 /* The code below is here to handle b/8734824
3052 * We create a IGraphicBufferProducer wrapper that forwards all calls
3053 * from the surfaceflinger thread to the calling binder thread, where they
3054 * are executed. This allows the calling thread in the calling process to be
3055 * reused and not depend on having "enough" binder threads to handle the
3058 class GraphicProducerWrapper : public BBinder, public MessageHandler {
3059 /* Parts of GraphicProducerWrapper are run on two different threads,
3060 * communicating by sending messages via Looper but also by shared member
3061 * data. Coherence maintenance is subtle and in places implicit (ugh).
3063 * Don't rely on Looper's sendMessage/handleMessage providing
3064 * release/acquire semantics for any data not actually in the Message.
3065 * Data going from surfaceflinger to binder threads needs to be
3066 * synchronized explicitly.
3068 * Barrier open/wait do provide release/acquire semantics. This provides
3069 * implicit synchronization for data coming back from binder to
3070 * surfaceflinger threads.
3073 sp<IGraphicBufferProducer> impl;
3089 * Called on surfaceflinger thread. This is called by our "fake"
3090 * BpGraphicBufferProducer. We package the data and reply Parcel and
3091 * forward them to the binder thread.
3093 virtual status_t transact(uint32_t code,
3094 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3097 this->reply = reply;
3099 // if we've exited, we run the message synchronously right here.
3100 // note (JH): as far as I can tell from looking at the code, this
3101 // never actually happens. if it does, i'm not sure if it happens
3102 // on the surfaceflinger or binder thread.
3103 handleMessage(Message(MSG_API_CALL));
3106 // Prevent stores to this->{code, data, reply} from being
3107 // reordered later than the construction of Message.
3108 atomic_thread_fence(memory_order_release);
3109 looper->sendMessage(this, Message(MSG_API_CALL));
3116 * here we run on the binder thread. All we've got to do is
3117 * call the real BpGraphicBufferProducer.
3119 virtual void handleMessage(const Message& message) {
3120 int what = message.what;
3121 // Prevent reads below from happening before the read from Message
3122 atomic_thread_fence(memory_order_acquire);
3123 if (what == MSG_API_CALL) {
3124 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3126 } else if (what == MSG_EXIT) {
3127 exitRequested = true;
3132 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3134 looper(new Looper(true)),
3136 exitRequested(false)
3140 status_t waitForResponse() {
3142 looper->pollOnce(-1);
3143 } while (!exitRequested);
3148 void exit(status_t result) {
3149 this->result = result;
3151 // Ensure this->result is visible to the binder thread before it
3152 // handles the message.
3153 atomic_thread_fence(memory_order_release);
3154 looper->sendMessage(this, Message(MSG_EXIT));
3159 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3160 const sp<IGraphicBufferProducer>& producer,
3161 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3162 uint32_t minLayerZ, uint32_t maxLayerZ,
3163 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3165 if (CC_UNLIKELY(display == 0))
3168 if (CC_UNLIKELY(producer == 0))
3171 // if we have secure windows on this display, never allow the screen capture
3172 // unless the producer interface is local (i.e.: we can take a screenshot for
3174 if (!IInterface::asBinder(producer)->localBinder()) {
3175 Mutex::Autolock _l(mStateLock);
3176 sp<const DisplayDevice> hw(getDisplayDevice(display));
3177 if (hw->getSecureLayerVisible()) {
3178 ALOGW("FB is protected: PERMISSION_DENIED");
3179 return PERMISSION_DENIED;
3183 // Convert to surfaceflinger's internal rotation type.
3184 Transform::orientation_flags rotationFlags;
3186 case ISurfaceComposer::eRotateNone:
3187 rotationFlags = Transform::ROT_0;
3189 case ISurfaceComposer::eRotate90:
3190 rotationFlags = Transform::ROT_90;
3192 case ISurfaceComposer::eRotate180:
3193 rotationFlags = Transform::ROT_180;
3195 case ISurfaceComposer::eRotate270:
3196 rotationFlags = Transform::ROT_270;
3199 rotationFlags = Transform::ROT_0;
3200 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3204 class MessageCaptureScreen : public MessageBase {
3205 SurfaceFlinger* flinger;
3206 sp<IBinder> display;
3207 sp<IGraphicBufferProducer> producer;
3209 uint32_t reqWidth, reqHeight;
3210 uint32_t minLayerZ,maxLayerZ;
3211 bool useIdentityTransform;
3212 Transform::orientation_flags rotation;
3215 MessageCaptureScreen(SurfaceFlinger* flinger,
3216 const sp<IBinder>& display,
3217 const sp<IGraphicBufferProducer>& producer,
3218 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3219 uint32_t minLayerZ, uint32_t maxLayerZ,
3220 bool useIdentityTransform, Transform::orientation_flags rotation)
3221 : flinger(flinger), display(display), producer(producer),
3222 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3223 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3224 useIdentityTransform(useIdentityTransform),
3226 result(PERMISSION_DENIED)
3229 status_t getResult() const {
3232 virtual bool handler() {
3233 Mutex::Autolock _l(flinger->mStateLock);
3234 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3235 result = flinger->captureScreenImplLocked(hw, producer,
3236 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3237 useIdentityTransform, rotation);
3238 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3243 // make sure to process transactions before screenshots -- a transaction
3244 // might already be pending but scheduled for VSYNC; this guarantees we
3245 // will handle it before the screenshot. When VSYNC finally arrives
3246 // the scheduled transaction will be a no-op. If no transactions are
3247 // scheduled at this time, this will end-up being a no-op as well.
3248 mEventQueue.invalidateTransactionNow();
3250 // this creates a "fake" BBinder which will serve as a "fake" remote
3251 // binder to receive the marshaled calls and forward them to the
3252 // real remote (a BpGraphicBufferProducer)
3253 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3255 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3256 // which does the marshaling work forwards to our "fake remote" above.
3257 sp<MessageBase> msg = new MessageCaptureScreen(this,
3258 display, IGraphicBufferProducer::asInterface( wrapper ),
3259 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3260 useIdentityTransform, rotationFlags);
3262 status_t res = postMessageAsync(msg);
3263 if (res == NO_ERROR) {
3264 res = wrapper->waitForResponse();
3270 void SurfaceFlinger::renderScreenImplLocked(
3271 const sp<const DisplayDevice>& hw,
3272 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3273 uint32_t minLayerZ, uint32_t maxLayerZ,
3274 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3277 RenderEngine& engine(getRenderEngine());
3279 // get screen geometry
3280 const int32_t hw_w = hw->getWidth();
3281 const int32_t hw_h = hw->getHeight();
3282 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3283 static_cast<int32_t>(reqHeight) != hw_h;
3285 // if a default or invalid sourceCrop is passed in, set reasonable values
3286 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3287 !sourceCrop.isValid()) {
3288 sourceCrop.setLeftTop(Point(0, 0));
3289 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3292 // ensure that sourceCrop is inside screen
3293 if (sourceCrop.left < 0) {
3294 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3296 if (sourceCrop.right > hw_w) {
3297 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3299 if (sourceCrop.top < 0) {
3300 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3302 if (sourceCrop.bottom > hw_h) {
3303 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3306 // make sure to clear all GL error flags
3307 engine.checkErrors();
3309 // set-up our viewport
3310 engine.setViewportAndProjection(
3311 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3312 engine.disableTexturing();
3314 // redraw the screen entirely...
3315 engine.clearWithColor(0, 0, 0, 1);
3317 const LayerVector& layers( mDrawingState.layersSortedByZ );
3318 const size_t count = layers.size();
3319 for (size_t i=0 ; i<count ; ++i) {
3320 const sp<Layer>& layer(layers[i]);
3321 const Layer::State& state(layer->getDrawingState());
3322 if (state.layerStack == hw->getLayerStack()) {
3323 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3324 if (canDrawLayerinScreenShot(hw,layer)) {
3325 if (filtering) layer->setFiltering(true);
3326 layer->draw(hw, useIdentityTransform);
3327 if (filtering) layer->setFiltering(false);
3333 // compositionComplete is needed for older driver
3334 hw->compositionComplete();
3335 hw->setViewportAndProjection();
3339 status_t SurfaceFlinger::captureScreenImplLocked(
3340 const sp<const DisplayDevice>& hw,
3341 const sp<IGraphicBufferProducer>& producer,
3342 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3343 uint32_t minLayerZ, uint32_t maxLayerZ,
3344 bool useIdentityTransform, Transform::orientation_flags rotation)
3348 // get screen geometry
3349 uint32_t hw_w = hw->getWidth();
3350 uint32_t hw_h = hw->getHeight();
3352 if (rotation & Transform::ROT_90) {
3353 std::swap(hw_w, hw_h);
3356 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3357 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3358 reqWidth, reqHeight, hw_w, hw_h);
3362 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3363 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3365 // create a surface (because we're a producer, and we need to
3366 // dequeue/queue a buffer)
3367 sp<Surface> sur = new Surface(producer, false);
3368 ANativeWindow* window = sur.get();
3370 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3371 if (result == NO_ERROR) {
3372 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3373 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3376 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3377 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3378 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3379 err |= native_window_set_usage(window, usage);
3381 if (err == NO_ERROR) {
3382 ANativeWindowBuffer* buffer;
3383 /* TODO: Once we have the sync framework everywhere this can use
3384 * server-side waits on the fence that dequeueBuffer returns.
3386 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3387 if (result == NO_ERROR) {
3389 // create an EGLImage from the buffer so we can later
3390 // turn it into a texture
3391 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3392 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3393 if (image != EGL_NO_IMAGE_KHR) {
3394 // this binds the given EGLImage as a framebuffer for the
3395 // duration of this scope.
3396 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3397 if (imageBond.getStatus() == NO_ERROR) {
3398 // this will in fact render into our dequeued buffer
3399 // via an FBO, which means we didn't have to create
3400 // an EGLSurface and therefore we're not
3401 // dependent on the context's EGLConfig.
3402 renderScreenImplLocked(
3403 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3404 useIdentityTransform, rotation);
3406 // Attempt to create a sync khr object that can produce a sync point. If that
3407 // isn't available, create a non-dupable sync object in the fallback path and
3408 // wait on it directly.
3410 if (!DEBUG_SCREENSHOTS) {
3411 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3412 // native fence fd will not be populated until flush() is done.
3413 getRenderEngine().flush();
3415 sync = EGL_NO_SYNC_KHR;
3417 if (sync != EGL_NO_SYNC_KHR) {
3419 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3420 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3421 ALOGW("captureScreen: failed to dup sync khr object");
3424 eglDestroySyncKHR(mEGLDisplay, sync);
3427 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3428 if (sync != EGL_NO_SYNC_KHR) {
3429 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3430 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3431 EGLint eglErr = eglGetError();
3432 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3433 ALOGW("captureScreen: fence wait timed out");
3435 ALOGW_IF(eglErr != EGL_SUCCESS,
3436 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3438 eglDestroySyncKHR(mEGLDisplay, sync);
3440 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3443 if (DEBUG_SCREENSHOTS) {
3444 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3445 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3446 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3447 hw, minLayerZ, maxLayerZ);
3452 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3453 result = INVALID_OPERATION;
3455 // destroy our image
3456 eglDestroyImageKHR(mEGLDisplay, image);
3460 // queueBuffer takes ownership of syncFd
3461 result = window->queueBuffer(window, buffer, syncFd);
3466 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3472 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3473 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3474 if (DEBUG_SCREENSHOTS) {
3475 for (size_t y=0 ; y<h ; y++) {
3476 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3477 for (size_t x=0 ; x<w ; x++) {
3478 if (p[x] != 0xFF000000) return;
3481 ALOGE("*** we just took a black screenshot ***\n"
3482 "requested minz=%d, maxz=%d, layerStack=%d",
3483 minLayerZ, maxLayerZ, hw->getLayerStack());
3484 const LayerVector& layers( mDrawingState.layersSortedByZ );
3485 const size_t count = layers.size();
3486 for (size_t i=0 ; i<count ; ++i) {
3487 const sp<Layer>& layer(layers[i]);
3488 const Layer::State& state(layer->getDrawingState());
3489 const bool visible = (state.layerStack == hw->getLayerStack())
3490 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3491 && (layer->isVisible());
3492 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3493 visible ? '+' : '-',
3494 i, layer->getName().string(), state.layerStack, state.z,
3495 layer->isVisible(), state.flags, state.alpha);
3500 /* ------------------------------------------------------------------------
3504 bool SurfaceFlinger::updateLayerVisibleNonTransparentRegion(const int& /*dpy*/,
3505 const sp<Layer>& layer, bool& /*bIgnoreLayers*/, int& /*indexLOI*/,
3506 uint32_t layerStack, const int& /*i*/) {
3508 const Layer::State& s(layer->getDrawingState());
3510 // only consider the layers on the given layer stack
3511 if (s.layerStack != layerStack)
3517 bool SurfaceFlinger::canDrawLayerinScreenShot(
3518 const sp<const DisplayDevice>& /*hw*/,
3519 const sp<Layer>& layer) {
3520 return layer->isVisible();
3523 // ---------------------------------------------------------------------------
3525 SurfaceFlinger::LayerVector::LayerVector() {
3528 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3529 : SortedVector<sp<Layer> >(rhs) {
3532 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3533 const void* rhs) const
3535 // sort layers per layer-stack, then by z-order and finally by sequence
3536 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3537 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3539 uint32_t ls = l->getCurrentState().layerStack;
3540 uint32_t rs = r->getCurrentState().layerStack;
3544 uint32_t lz = l->getCurrentState().z;
3545 uint32_t rz = r->getCurrentState().z;
3549 return l->sequence - r->sequence;
3552 // ---------------------------------------------------------------------------
3554 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3555 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
3558 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3559 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
3560 viewport.makeInvalid();
3561 frame.makeInvalid();
3564 // ---------------------------------------------------------------------------
3566 }; // namespace android
3569 #if defined(__gl_h_)
3570 #error "don't include gl/gl.h in this file"
3573 #if defined(__gl2_h_)
3574 #error "don't include gl2/gl2.h in this file"