• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 
17 #ifndef ANDROID_SURFACE_FLINGER_H
18 #define ANDROID_SURFACE_FLINGER_H
19 
20 #include <stdint.h>
21 #include <sys/types.h>
22 
23 #include <EGL/egl.h>
24 
25 /*
26  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
27  */
28 
29 #include <cutils/compiler.h>
30 
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>
37 
38 #include <binder/IMemory.h>
39 
40 #include <ui/PixelFormat.h>
41 #include <ui/mat4.h>
42 
43 #include <gui/ISurfaceComposer.h>
44 #include <gui/ISurfaceComposerClient.h>
45 
46 #include <hardware/hwcomposer_defs.h>
47 
48 #include <private/gui/LayerState.h>
49 
50 #include "Barrier.h"
51 #include "DisplayDevice.h"
52 #include "DispSync.h"
53 #include "FrameTracker.h"
54 #include "MessageQueue.h"
55 
56 #include "DisplayHardware/HWComposer.h"
57 #include "Effects/Daltonizer.h"
58 
59 namespace android {
60 
61 // ---------------------------------------------------------------------------
62 
63 class Client;
64 class DisplayEventConnection;
65 class EventThread;
66 class IGraphicBufferAlloc;
67 class Layer;
68 class LayerDim;
69 class Surface;
70 class RenderEngine;
71 class EventControlThread;
72 
73 // ---------------------------------------------------------------------------
74 
75 enum {
76     eTransactionNeeded        = 0x01,
77     eTraversalNeeded          = 0x02,
78     eDisplayTransactionNeeded = 0x04,
79     eTransactionMask          = 0x07
80 };
81 
82 class SurfaceFlinger : public BnSurfaceComposer,
83                        private IBinder::DeathRecipient,
84                        private HWComposer::EventHandler
85 {
86 public:
getServiceName()87     static char const* getServiceName() ANDROID_API {
88         return "SurfaceFlinger";
89     }
90 
91     SurfaceFlinger() ANDROID_API;
92 
93     // must be called before clients can connect
94     void init() ANDROID_API;
95 
96     // starts SurfaceFlinger main loop in the current thread
97     void run() ANDROID_API;
98 
99     enum {
100         EVENT_VSYNC = HWC_EVENT_VSYNC
101     };
102 
103     // post an asynchronous message to the main thread
104     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
105 
106     // post a synchronous message to the main thread
107     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
108 
109     // force full composition on all displays
110     void repaintEverything();
111 
112     // returns the default Display
getDefaultDisplayDevice()113     sp<const DisplayDevice> getDefaultDisplayDevice() const {
114         return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
115     }
116 
117     // utility function to delete a texture on the main thread
118     void deleteTextureAsync(uint32_t texture);
119 
120     // enable/disable h/w composer event
121     // TODO: this should be made accessible only to EventThread
122     void eventControl(int disp, int event, int enabled);
123 
124     // called on the main thread by MessageQueue when an internal message
125     // is received
126     // TODO: this should be made accessible only to MessageQueue
127     void onMessageReceived(int32_t what);
128 
129     // for debugging only
130     // TODO: this should be made accessible only to HWComposer
131     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
132 
getRenderEngine()133     RenderEngine& getRenderEngine() const {
134         return *mRenderEngine;
135     }
136 
137 private:
138     friend class Client;
139     friend class DisplayEventConnection;
140     friend class Layer;
141     friend class MonitoredProducer;
142 
143     // This value is specified in number of frames.  Log frame stats at most
144     // every half hour.
145     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
146 
147     // We're reference counted, never destroy SurfaceFlinger directly
148     virtual ~SurfaceFlinger();
149 
150     /* ------------------------------------------------------------------------
151      * Internal data structures
152      */
153 
154     class LayerVector : public SortedVector< sp<Layer> > {
155     public:
156         LayerVector();
157         LayerVector(const LayerVector& rhs);
158         virtual int do_compare(const void* lhs, const void* rhs) const;
159     };
160 
161     struct DisplayDeviceState {
162         DisplayDeviceState();
163         DisplayDeviceState(DisplayDevice::DisplayType type);
isValidDisplayDeviceState164         bool isValid() const { return type >= 0; }
isMainDisplayDisplayDeviceState165         bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
isVirtualDisplayDisplayDeviceState166         bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
167         DisplayDevice::DisplayType type;
168         sp<IGraphicBufferProducer> surface;
169         uint32_t layerStack;
170         Rect viewport;
171         Rect frame;
172         uint8_t orientation;
173         uint32_t width, height;
174         String8 displayName;
175         bool isSecure;
176     };
177 
178     struct State {
179         LayerVector layersSortedByZ;
180         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
181     };
182 
183     /* ------------------------------------------------------------------------
184      * IBinder interface
185      */
186     virtual status_t onTransact(uint32_t code, const Parcel& data,
187         Parcel* reply, uint32_t flags);
188     virtual status_t dump(int fd, const Vector<String16>& args);
189 
190     /* ------------------------------------------------------------------------
191      * ISurfaceComposer interface
192      */
193     virtual sp<ISurfaceComposerClient> createConnection();
194     virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
195     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
196     virtual void destroyDisplay(const sp<IBinder>& display);
197     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
198     virtual void setTransactionState(const Vector<ComposerState>& state,
199             const Vector<DisplayState>& displays, uint32_t flags);
200     virtual void bootFinished();
201     virtual bool authenticateSurfaceTexture(
202         const sp<IGraphicBufferProducer>& bufferProducer) const;
203     virtual sp<IDisplayEventConnection> createDisplayEventConnection();
204     virtual status_t captureScreen(const sp<IBinder>& display,
205             const sp<IGraphicBufferProducer>& producer,
206             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
207             uint32_t minLayerZ, uint32_t maxLayerZ,
208             bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
209     virtual status_t getDisplayStats(const sp<IBinder>& display,
210             DisplayStatInfo* stats);
211     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
212             Vector<DisplayInfo>* configs);
213     virtual int getActiveConfig(const sp<IBinder>& display);
214     virtual void setPowerMode(const sp<IBinder>& display, int mode);
215     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
216     virtual status_t clearAnimationFrameStats();
217     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
218 
219     /* ------------------------------------------------------------------------
220      * DeathRecipient interface
221      */
222     virtual void binderDied(const wp<IBinder>& who);
223 
224     /* ------------------------------------------------------------------------
225      * RefBase interface
226      */
227     virtual void onFirstRef();
228 
229     /* ------------------------------------------------------------------------
230      * HWComposer::EventHandler interface
231      */
232     virtual void onVSyncReceived(int type, nsecs_t timestamp);
233     virtual void onHotplugReceived(int disp, bool connected);
234 
235     /* ------------------------------------------------------------------------
236      * Message handling
237      */
238     void waitForEvent();
239     void signalTransaction();
240     void signalLayerUpdate();
241     void signalRefresh();
242 
243     // called on the main thread in response to initializeDisplays()
244     void onInitializeDisplays();
245     // called on the main thread in response to setActiveConfig()
246     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
247     // called on the main thread in response to setPowerMode()
248     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
249 
250     void handleMessageTransaction();
251     void handleMessageInvalidate();
252     void handleMessageRefresh();
253 
254     void handleTransaction(uint32_t transactionFlags);
255     void handleTransactionLocked(uint32_t transactionFlags);
256 
257     void updateCursorAsync();
258 
259     /* handlePageFilp: this is were we latch a new buffer
260      * if available and compute the dirty region.
261      */
262     void handlePageFlip();
263 
264     /* ------------------------------------------------------------------------
265      * Transactions
266      */
267     uint32_t getTransactionFlags(uint32_t flags);
268     uint32_t peekTransactionFlags(uint32_t flags);
269     uint32_t setTransactionFlags(uint32_t flags);
270     void commitTransaction();
271     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
272     uint32_t setDisplayStateLocked(const DisplayState& s);
273 
274     /* ------------------------------------------------------------------------
275      * Layer management
276      */
277     status_t createLayer(const String8& name, const sp<Client>& client,
278             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
279             sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
280 
281     status_t createNormalLayer(const sp<Client>& client, const String8& name,
282             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
283             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
284             sp<Layer>* outLayer);
285 
286     status_t createDimLayer(const sp<Client>& client, const String8& name,
287             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
288             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
289 
290     // called in response to the window-manager calling
291     // ISurfaceComposerClient::destroySurface()
292     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
293 
294     // called when all clients have released all their references to
295     // this layer meaning it is entirely safe to destroy all
296     // resources associated to this layer.
297     status_t onLayerDestroyed(const wp<Layer>& layer);
298 
299     // remove a layer from SurfaceFlinger immediately
300     status_t removeLayer(const sp<Layer>& layer);
301 
302     // add a layer to SurfaceFlinger
303     void addClientLayer(const sp<Client>& client,
304             const sp<IBinder>& handle,
305             const sp<IGraphicBufferProducer>& gbc,
306             const sp<Layer>& lbc);
307 
308     /* ------------------------------------------------------------------------
309      * Boot animation, on/off animations and screen capture
310      */
311 
312     void startBootAnim();
313 
314     void renderScreenImplLocked(
315             const sp<const DisplayDevice>& hw,
316             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
317             uint32_t minLayerZ, uint32_t maxLayerZ,
318             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
319 
320     status_t captureScreenImplLocked(
321             const sp<const DisplayDevice>& hw,
322             const sp<IGraphicBufferProducer>& producer,
323             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
324             uint32_t minLayerZ, uint32_t maxLayerZ,
325             bool useIdentityTransform, Transform::orientation_flags rotation);
326 
327     /* ------------------------------------------------------------------------
328      * EGL
329      */
330     size_t getMaxTextureSize() const;
331     size_t getMaxViewportDims() const;
332 
333     /* ------------------------------------------------------------------------
334      * Display and layer stack management
335      */
336     // called when starting, or restarting after system_server death
337     void initializeDisplays();
338 
339     // Create an IBinder for a builtin display and add it to current state
340     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
341 
342     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDevice(const wp<IBinder> & dpy)343     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
344         return mDisplays.valueFor(dpy);
345     }
346 
347     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDevice(const wp<IBinder> & dpy)348     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
349         return mDisplays.valueFor(dpy);
350     }
351 
352     // mark a region of a layer stack dirty. this updates the dirty
353     // region of all screens presenting this layer stack.
354     void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
355 
356     // allocate a h/w composer display id
357     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
358 
359     /* ------------------------------------------------------------------------
360      * H/W composer
361      */
362 
getHwComposer()363     HWComposer& getHwComposer() const { return *mHwc; }
364 
365     /* ------------------------------------------------------------------------
366      * Compositing
367      */
368     void invalidateHwcGeometry();
369     static void computeVisibleRegions(
370             const LayerVector& currentLayers, uint32_t layerStack,
371             Region& dirtyRegion, Region& opaqueRegion);
372 
373     void preComposition();
374     void postComposition();
375     void rebuildLayerStacks();
376     void setUpHWComposer();
377     void doComposition();
378     void doDebugFlashRegions();
379     void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
380 
381     // compose surfaces for display hw. this fails if using GL and the surface
382     // has been destroyed and is no longer valid.
383     bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
384 
385     void postFramebuffer();
386     void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
387 
388     /* ------------------------------------------------------------------------
389      * Display management
390      */
391 
392     /* ------------------------------------------------------------------------
393      * VSync
394      */
395      void enableHardwareVsync();
396      void disableHardwareVsync(bool makeUnavailable);
397      void resyncToHardwareVsync(bool makeAvailable);
398 
399     /* ------------------------------------------------------------------------
400      * Debugging & dumpsys
401      */
402     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
403     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
404     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
405     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
406     bool startDdmConnection();
407     static void appendSfConfigString(String8& result);
408     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
409             const sp<const DisplayDevice>& hw,
410             uint32_t minLayerZ, uint32_t maxLayerZ);
411 
412     void logFrameStats();
413 
414     /* ------------------------------------------------------------------------
415      * Attributes
416      */
417 
418     // access must be protected by mStateLock
419     mutable Mutex mStateLock;
420     State mCurrentState;
421     volatile int32_t mTransactionFlags;
422     Condition mTransactionCV;
423     bool mTransactionPending;
424     bool mAnimTransactionPending;
425     Vector< sp<Layer> > mLayersPendingRemoval;
426     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
427 
428     // protected by mStateLock (but we could use another lock)
429     bool mLayersRemoved;
430 
431     // access must be protected by mInvalidateLock
432     volatile int32_t mRepaintEverything;
433 
434     // constant members (no synchronization needed for access)
435     HWComposer* mHwc;
436     RenderEngine* mRenderEngine;
437     nsecs_t mBootTime;
438     bool mGpuToCpuSupported;
439     sp<EventThread> mEventThread;
440     sp<EventThread> mSFEventThread;
441     sp<EventControlThread> mEventControlThread;
442     EGLContext mEGLContext;
443     EGLDisplay mEGLDisplay;
444     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
445 
446     // Can only accessed from the main thread, these members
447     // don't need synchronization
448     State mDrawingState;
449     bool mVisibleRegionsDirty;
450     bool mHwWorkListDirty;
451     bool mAnimCompositionPending;
452 
453     // this may only be written from the main thread with mStateLock held
454     // it may be read from other threads with mStateLock held
455     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
456 
457     // don't use a lock for these, we don't care
458     int mDebugRegion;
459     int mDebugDDMS;
460     int mDebugDisableHWC;
461     int mDebugDisableTransformHint;
462     volatile nsecs_t mDebugInSwapBuffers;
463     nsecs_t mLastSwapBufferTime;
464     volatile nsecs_t mDebugInTransaction;
465     nsecs_t mLastTransactionTime;
466     bool mBootFinished;
467 
468     // these are thread safe
469     mutable MessageQueue mEventQueue;
470     FrameTracker mAnimFrameTracker;
471     DispSync mPrimaryDispSync;
472 
473     // protected by mDestroyedLayerLock;
474     mutable Mutex mDestroyedLayerLock;
475     Vector<Layer const *> mDestroyedLayers;
476 
477     // protected by mHWVsyncLock
478     Mutex mHWVsyncLock;
479     bool mPrimaryHWVsyncEnabled;
480     bool mHWVsyncAvailable;
481 
482     /* ------------------------------------------------------------------------
483      * Feature prototyping
484      */
485 
486     Daltonizer mDaltonizer;
487     bool mDaltonize;
488 
489     mat4 mColorMatrix;
490     bool mHasColorMatrix;
491 };
492 
493 }; // namespace android
494 
495 #endif // ANDROID_SURFACE_FLINGER_H
496