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 #ifndef ANDROID_SURFACE_FLINGER_H
18 #define ANDROID_SURFACE_FLINGER_H
21 #include <sys/types.h>
26 * NOTE: Make sure this file doesn't include anything from <gl/ > or <gl2/ >
29 #include <cutils/compiler.h>
31 #include <utils/Atomic.h>
32 #include <utils/Errors.h>
33 #include <utils/KeyedVector.h>
34 #include <utils/RefBase.h>
35 #include <utils/SortedVector.h>
36 #include <utils/threads.h>
38 #include <binder/IMemory.h>
40 #include <ui/PixelFormat.h>
43 #include <gui/ISurfaceComposer.h>
44 #include <gui/ISurfaceComposerClient.h>
46 #include <hardware/hwcomposer_defs.h>
48 #include <private/gui/LayerState.h>
51 #include "DisplayDevice.h"
53 #include "FrameTracker.h"
54 #include "MessageQueue.h"
56 #include "DisplayHardware/HWComposer.h"
57 #include "Effects/Daltonizer.h"
59 #include "FrameRateHelper.h"
63 // ---------------------------------------------------------------------------
66 class DisplayEventConnection;
68 class IGraphicBufferAlloc;
74 class EventControlThread;
76 // ---------------------------------------------------------------------------
79 eTransactionNeeded = 0x01,
80 eTraversalNeeded = 0x02,
81 eDisplayTransactionNeeded = 0x04,
82 eTransactionMask = 0x07
85 class SurfaceFlinger : public BnSurfaceComposer,
86 private IBinder::DeathRecipient,
87 private HWComposer::EventHandler
91 friend class ExSurfaceFlinger;
94 static char const* getServiceName() ANDROID_API {
95 return "SurfaceFlinger";
98 SurfaceFlinger() ANDROID_API;
100 // must be called before clients can connect
101 void init() ANDROID_API;
103 // starts SurfaceFlinger main loop in the current thread
104 void run() ANDROID_API;
107 EVENT_VSYNC = HWC_EVENT_VSYNC
110 // post an asynchronous message to the main thread
111 status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
113 // post a synchronous message to the main thread
114 status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
116 // force full composition on all displays
117 void repaintEverything();
119 // returns the default Display
120 sp<const DisplayDevice> getDefaultDisplayDevice() const {
121 return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
124 // utility function to delete a texture on the main thread
125 void deleteTextureAsync(uint32_t texture);
127 // enable/disable h/w composer event
128 // TODO: this should be made accessible only to EventThread
129 void eventControl(int disp, int event, int enabled);
131 // called on the main thread by MessageQueue when an internal message
133 // TODO: this should be made accessible only to MessageQueue
134 void onMessageReceived(int32_t what);
136 // for debugging only
137 // TODO: this should be made accessible only to HWComposer
138 const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
140 RenderEngine& getRenderEngine() const {
141 return *mRenderEngine;
144 void screenReleased(const sp<IBinder>& display);
145 void screenAcquired(const sp<IBinder>& display);
149 friend class DisplayEventConnection;
151 friend class LayerDim;
153 friend class ExLayer;
155 friend class MonitoredProducer;
156 friend class LayerBlur;
158 // This value is specified in number of frames. Log frame stats at most
160 enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
162 static const size_t MAX_LAYERS = 4096;
164 // We're reference counted, never destroy SurfaceFlinger directly
165 virtual ~SurfaceFlinger();
167 /* ------------------------------------------------------------------------
168 * Internal data structures
171 class LayerVector : public SortedVector< sp<Layer> > {
174 LayerVector(const LayerVector& rhs);
175 virtual int do_compare(const void* lhs, const void* rhs) const;
178 struct DisplayDeviceState {
179 DisplayDeviceState();
180 DisplayDeviceState(DisplayDevice::DisplayType type);
181 bool isValid() const { return type >= 0; }
182 bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
183 bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
184 DisplayDevice::DisplayType type;
185 sp<IGraphicBufferProducer> surface;
190 uint32_t width, height;
196 LayerVector layersSortedByZ;
197 DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
200 /* ------------------------------------------------------------------------
203 virtual status_t onTransact(uint32_t code, const Parcel& data,
204 Parcel* reply, uint32_t flags);
205 virtual status_t dump(int fd, const Vector<String16>& args);
207 /* ------------------------------------------------------------------------
208 * ISurfaceComposer interface
210 virtual sp<ISurfaceComposerClient> createConnection();
211 virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
212 virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
213 virtual void destroyDisplay(const sp<IBinder>& display);
214 virtual sp<IBinder> getBuiltInDisplay(int32_t id);
215 virtual void setTransactionState(const Vector<ComposerState>& state,
216 const Vector<DisplayState>& displays, uint32_t flags);
217 virtual void bootFinished();
218 virtual bool authenticateSurfaceTexture(
219 const sp<IGraphicBufferProducer>& bufferProducer) const;
220 virtual sp<IDisplayEventConnection> createDisplayEventConnection();
221 virtual status_t captureScreen(const sp<IBinder>& display,
222 const sp<IGraphicBufferProducer>& producer,
223 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
224 uint32_t minLayerZ, uint32_t maxLayerZ,
225 bool useIdentityTransform, ISurfaceComposer::Rotation rotation,
227 virtual status_t getDisplayStats(const sp<IBinder>& display,
228 DisplayStatInfo* stats);
229 virtual status_t getDisplayConfigs(const sp<IBinder>& display,
230 Vector<DisplayInfo>* configs);
231 virtual int getActiveConfig(const sp<IBinder>& display);
232 virtual void setPowerMode(const sp<IBinder>& display, int mode);
233 virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
234 virtual status_t clearAnimationFrameStats();
235 virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
237 /* ------------------------------------------------------------------------
238 * DeathRecipient interface
240 virtual void binderDied(const wp<IBinder>& who);
242 /* ------------------------------------------------------------------------
245 virtual void onFirstRef();
247 /* ------------------------------------------------------------------------
248 * HWComposer::EventHandler interface
250 virtual void onVSyncReceived(int type, nsecs_t timestamp);
251 virtual void onHotplugReceived(int disp, bool connected);
253 /* ------------------------------------------------------------------------
256 virtual void updateExtendedMode() { }
258 virtual void getIndexLOI(size_t /*dpy*/,
259 const LayerVector& /*currentLayers*/,
260 bool& /*bIgnoreLayers*/,
261 int& /*indexLOI*/) { }
263 virtual bool updateLayerVisibleNonTransparentRegion(
264 const int& dpy, const sp<Layer>& layer,
265 bool& bIgnoreLayers, int& indexLOI,
266 uint32_t layerStack, const int& i);
268 virtual void delayDPTransactionIfNeeded(
269 const Vector<DisplayState>& /*displays*/) { }
271 virtual bool canDrawLayerinScreenShot(
272 const sp<const DisplayDevice>& hw,
273 const sp<Layer>& layer);
275 virtual void isfreezeSurfacePresent(
276 bool& freezeSurfacePresent,
277 const sp<const DisplayDevice>& /*hw*/,
278 const int32_t& /*id*/) { freezeSurfacePresent = false; }
280 virtual void setOrientationEventControl(
281 bool& /*freezeSurfacePresent*/,
282 const int32_t& /*id*/) { }
284 virtual void updateVisibleRegionsDirty() { }
286 virtual void drawWormHoleIfRequired(HWComposer::LayerListIterator &cur,
287 const HWComposer::LayerListIterator &end,
288 const sp<const DisplayDevice>& hw,
289 const Region& region);
290 /* ------------------------------------------------------------------------
294 void signalTransaction();
295 void signalLayerUpdate();
296 void signalRefresh();
298 // called on the main thread in response to initializeDisplays()
299 void onInitializeDisplays();
300 // called on the main thread in response to setActiveConfig()
301 void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
302 // called on the main thread in response to setPowerMode()
303 void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
305 // Returns whether the transaction actually modified any state
306 bool handleMessageTransaction();
308 // Returns whether a new buffer has been latched (see handlePageFlip())
309 bool handleMessageInvalidate();
311 void handleMessageRefresh();
313 void handleTransaction(uint32_t transactionFlags);
314 void handleTransactionLocked(uint32_t transactionFlags);
316 void updateCursorAsync();
318 /* handlePageFlip - latch a new buffer if available and compute the dirty
319 * region. Returns whether a new buffer has been latched, i.e., whether it
320 * is necessary to perform a refresh during this vsync.
322 bool handlePageFlip();
324 /* ------------------------------------------------------------------------
327 uint32_t getTransactionFlags(uint32_t flags);
328 uint32_t peekTransactionFlags(uint32_t flags);
329 uint32_t setTransactionFlags(uint32_t flags);
330 void commitTransaction();
331 uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
332 uint32_t setDisplayStateLocked(const DisplayState& s);
334 /* ------------------------------------------------------------------------
337 status_t createLayer(const String8& name, const sp<Client>& client,
338 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
339 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
341 status_t createNormalLayer(const sp<Client>& client, const String8& name,
342 uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
343 sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
344 sp<Layer>* outLayer);
346 status_t createDimLayer(const sp<Client>& client, const String8& name,
347 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
348 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
350 status_t createBlurLayer(const sp<Client>& client, const String8& name,
351 uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
352 sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
354 // called in response to the window-manager calling
355 // ISurfaceComposerClient::destroySurface()
356 status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
358 // called when all clients have released all their references to
359 // this layer meaning it is entirely safe to destroy all
360 // resources associated to this layer.
361 status_t onLayerDestroyed(const wp<Layer>& layer);
363 // remove a layer from SurfaceFlinger immediately
364 status_t removeLayer(const sp<Layer>& layer);
366 // add a layer to SurfaceFlinger
367 status_t addClientLayer(const sp<Client>& client,
368 const sp<IBinder>& handle,
369 const sp<IGraphicBufferProducer>& gbc,
370 const sp<Layer>& lbc);
372 /* ------------------------------------------------------------------------
373 * Boot animation, on/off animations and screen capture
376 void startBootAnim();
378 void renderScreenImplLocked(
379 const sp<const DisplayDevice>& hw,
380 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
381 uint32_t minLayerZ, uint32_t maxLayerZ,
382 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
384 status_t captureScreenImplLocked(
385 const sp<const DisplayDevice>& hw,
386 const sp<IGraphicBufferProducer>& producer,
387 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
388 uint32_t minLayerZ, uint32_t maxLayerZ,
389 bool useIdentityTransform, Transform::orientation_flags rotation,
392 /* ------------------------------------------------------------------------
395 size_t getMaxTextureSize() const;
396 size_t getMaxViewportDims() const;
398 /* ------------------------------------------------------------------------
399 * Display and layer stack management
401 // called when starting, or restarting after system_server death
402 void initializeDisplays();
404 // Create an IBinder for a builtin display and add it to current state
405 void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
407 // NOTE: can only be called from the main thread or with mStateLock held
408 sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
409 return mDisplays.valueFor(dpy);
412 // NOTE: can only be called from the main thread or with mStateLock held
413 sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
414 return mDisplays.valueFor(dpy);
417 // mark a region of a layer stack dirty. this updates the dirty
418 // region of all screens presenting this layer stack.
419 void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
421 // allocate a h/w composer display id
422 int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
424 /* ------------------------------------------------------------------------
428 HWComposer& getHwComposer() const { return *mHwc; }
430 /* ------------------------------------------------------------------------
433 void invalidateHwcGeometry();
434 void computeVisibleRegions(size_t dpy,
435 const LayerVector& currentLayers, uint32_t layerStack,
436 Region& dirtyRegion, Region& opaqueRegion);
438 void preComposition();
439 void postComposition();
440 void rebuildLayerStacks();
441 void setUpHWComposer();
442 void doComposition();
443 void doDebugFlashRegions();
444 void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
446 // compose surfaces for display hw. this fails if using GL and the surface
447 // has been destroyed and is no longer valid.
448 bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
450 void postFramebuffer();
451 void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
453 /* ------------------------------------------------------------------------
457 /* ------------------------------------------------------------------------
460 void enableHardwareVsync();
461 void disableHardwareVsync(bool makeUnavailable);
462 void resyncToHardwareVsync(bool makeAvailable);
464 /* ------------------------------------------------------------------------
465 * Debugging & dumpsys
467 void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
468 void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
469 void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
470 void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
471 bool startDdmConnection();
472 static void appendSfConfigString(String8& result);
473 void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
474 const sp<const DisplayDevice>& hw,
475 uint32_t minLayerZ, uint32_t maxLayerZ);
477 void logFrameStats();
479 void dumpStaticScreenStats(String8& result) const;
480 virtual void dumpDrawCycle(bool /* prePrepare */ ) { }
482 /* ------------------------------------------------------------------------
486 // access must be protected by mStateLock
487 mutable Mutex mStateLock;
489 volatile int32_t mTransactionFlags;
490 Condition mTransactionCV;
491 bool mTransactionPending;
492 bool mAnimTransactionPending;
493 Vector< sp<Layer> > mLayersPendingRemoval;
494 SortedVector< wp<IBinder> > mGraphicBufferProducerList;
496 // protected by mStateLock (but we could use another lock)
499 // access must be protected by mInvalidateLock
500 volatile int32_t mRepaintEverything;
502 // constant members (no synchronization needed for access)
504 RenderEngine* mRenderEngine;
506 bool mGpuToCpuSupported;
507 bool mDropMissedFrames;
508 sp<EventThread> mEventThread;
509 sp<EventThread> mSFEventThread;
510 sp<EventControlThread> mEventControlThread;
511 EGLContext mEGLContext;
512 EGLDisplay mEGLDisplay;
513 sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
515 // Can only accessed from the main thread, these members
516 // don't need synchronization
518 bool mVisibleRegionsDirty;
519 bool mHwWorkListDirty;
520 bool mAnimCompositionPending;
522 // this may only be written from the main thread with mStateLock held
523 // it may be read from other threads with mStateLock held
524 DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
526 // don't use a lock for these, we don't care
529 int mDebugDisableHWC;
530 int mDebugDisableTransformHint;
531 volatile nsecs_t mDebugInSwapBuffers;
532 nsecs_t mLastSwapBufferTime;
533 volatile nsecs_t mDebugInTransaction;
534 nsecs_t mLastTransactionTime;
536 bool mForceFullDamage;
538 // these are thread safe
539 mutable MessageQueue mEventQueue;
540 FrameTracker mAnimFrameTracker;
541 DispSync mPrimaryDispSync;
543 // protected by mDestroyedLayerLock;
544 mutable Mutex mDestroyedLayerLock;
545 Vector<Layer const *> mDestroyedLayers;
547 // protected by mHWVsyncLock
549 bool mPrimaryHWVsyncEnabled;
550 bool mHWVsyncAvailable;
552 /* ------------------------------------------------------------------------
553 * Feature prototyping
556 Daltonizer mDaltonizer;
560 bool mHasColorMatrix;
562 mat4 mSecondaryColorMatrix;
563 bool mHasSecondaryColorMatrix;
565 // Static screen stats
567 static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
568 nsecs_t mFrameBuckets[NUM_BUCKETS];
570 nsecs_t mLastSwapTime;
572 FrameRateHelper mFrameRateHelper;
575 * A number that increases on every new frame composition and screen capture.
576 * LayerBlur can speed up it's drawing by caching texture using this variable
577 * if multiple LayerBlur objects draw in one frame composition.
578 * In case of display mirroring, this variable should be increased on every display.
580 uint32_t mActiveFrameSequence;
584 }; // namespace android
586 #endif // ANDROID_SURFACE_FLINGER_H