OSDN Git Service

Merge "egl: Add EGL extension for front buffer auto-refresh mode" into nyc-dev
[android-x86/frameworks-native.git] / services / surfaceflinger / SurfaceFlinger.h
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:
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
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 #ifdef USE_HWC2
123     void setVsyncEnabled(int disp, int enabled);
124 #else
125     void eventControl(int disp, int event, int enabled);
126 #endif
127
128     // called on the main thread by MessageQueue when an internal message
129     // is received
130     // TODO: this should be made accessible only to MessageQueue
131     void onMessageReceived(int32_t what);
132
133     // for debugging only
134     // TODO: this should be made accessible only to HWComposer
135     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
136
137     RenderEngine& getRenderEngine() const {
138         return *mRenderEngine;
139     }
140
141 private:
142     friend class Client;
143     friend class DisplayEventConnection;
144     friend class Layer;
145     friend class MonitoredProducer;
146
147     // This value is specified in number of frames.  Log frame stats at most
148     // every half hour.
149     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
150
151     static const size_t MAX_LAYERS = 4096;
152
153     // We're reference counted, never destroy SurfaceFlinger directly
154     virtual ~SurfaceFlinger();
155
156     /* ------------------------------------------------------------------------
157      * Internal data structures
158      */
159
160     class LayerVector : public SortedVector< sp<Layer> > {
161     public:
162         LayerVector();
163         LayerVector(const LayerVector& rhs);
164         virtual int do_compare(const void* lhs, const void* rhs) const;
165     };
166
167     struct DisplayDeviceState {
168         DisplayDeviceState();
169         DisplayDeviceState(DisplayDevice::DisplayType type, bool isSecure);
170         bool isValid() const { return type >= 0; }
171         bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
172         bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
173         DisplayDevice::DisplayType type;
174         sp<IGraphicBufferProducer> surface;
175         uint32_t layerStack;
176         Rect viewport;
177         Rect frame;
178         uint8_t orientation;
179         uint32_t width, height;
180         String8 displayName;
181         bool isSecure;
182     };
183
184     struct State {
185         LayerVector layersSortedByZ;
186         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
187     };
188
189     /* ------------------------------------------------------------------------
190      * IBinder interface
191      */
192     virtual status_t onTransact(uint32_t code, const Parcel& data,
193         Parcel* reply, uint32_t flags);
194     virtual status_t dump(int fd, const Vector<String16>& args);
195
196     /* ------------------------------------------------------------------------
197      * ISurfaceComposer interface
198      */
199     virtual sp<ISurfaceComposerClient> createConnection();
200     virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
201     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
202     virtual void destroyDisplay(const sp<IBinder>& display);
203     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
204     virtual void setTransactionState(const Vector<ComposerState>& state,
205             const Vector<DisplayState>& displays, uint32_t flags);
206     virtual void bootFinished();
207     virtual bool authenticateSurfaceTexture(
208         const sp<IGraphicBufferProducer>& bufferProducer) const;
209     virtual sp<IDisplayEventConnection> createDisplayEventConnection();
210     virtual status_t captureScreen(const sp<IBinder>& display,
211             const sp<IGraphicBufferProducer>& producer,
212             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
213             uint32_t minLayerZ, uint32_t maxLayerZ,
214             bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
215     virtual status_t getDisplayStats(const sp<IBinder>& display,
216             DisplayStatInfo* stats);
217     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
218             Vector<DisplayInfo>* configs);
219     virtual int getActiveConfig(const sp<IBinder>& display);
220     virtual void setPowerMode(const sp<IBinder>& display, int mode);
221     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
222     virtual status_t clearAnimationFrameStats();
223     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
224
225     /* ------------------------------------------------------------------------
226      * DeathRecipient interface
227      */
228     virtual void binderDied(const wp<IBinder>& who);
229
230     /* ------------------------------------------------------------------------
231      * RefBase interface
232      */
233     virtual void onFirstRef();
234
235     /* ------------------------------------------------------------------------
236      * HWComposer::EventHandler interface
237      */
238     virtual void onVSyncReceived(int type, nsecs_t timestamp);
239     virtual void onHotplugReceived(int disp, bool connected);
240
241     /* ------------------------------------------------------------------------
242      * Message handling
243      */
244     void waitForEvent();
245     void signalTransaction();
246     void signalLayerUpdate();
247     void signalRefresh();
248
249     // called on the main thread in response to initializeDisplays()
250     void onInitializeDisplays();
251     // called on the main thread in response to setActiveConfig()
252     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
253     // called on the main thread in response to setPowerMode()
254     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
255
256     // Returns whether the transaction actually modified any state
257     bool handleMessageTransaction();
258
259     // Returns whether a new buffer has been latched (see handlePageFlip())
260     bool handleMessageInvalidate();
261
262     void handleMessageRefresh();
263
264     void handleTransaction(uint32_t transactionFlags);
265     void handleTransactionLocked(uint32_t transactionFlags);
266
267     void updateCursorAsync();
268
269     /* handlePageFlip - latch a new buffer if available and compute the dirty
270      * region. Returns whether a new buffer has been latched, i.e., whether it
271      * is necessary to perform a refresh during this vsync.
272      */
273     bool handlePageFlip();
274
275     /* ------------------------------------------------------------------------
276      * Transactions
277      */
278     uint32_t getTransactionFlags(uint32_t flags);
279     uint32_t peekTransactionFlags(uint32_t flags);
280     uint32_t setTransactionFlags(uint32_t flags);
281     void commitTransaction();
282     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
283     uint32_t setDisplayStateLocked(const DisplayState& s);
284
285     /* ------------------------------------------------------------------------
286      * Layer management
287      */
288     status_t createLayer(const String8& name, const sp<Client>& client,
289             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
290             sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
291
292     status_t createNormalLayer(const sp<Client>& client, const String8& name,
293             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
294             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
295             sp<Layer>* outLayer);
296
297     status_t createDimLayer(const sp<Client>& client, const String8& name,
298             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
299             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
300
301     // called in response to the window-manager calling
302     // ISurfaceComposerClient::destroySurface()
303     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
304
305     // called when all clients have released all their references to
306     // this layer meaning it is entirely safe to destroy all
307     // resources associated to this layer.
308     status_t onLayerDestroyed(const wp<Layer>& layer);
309
310     // remove a layer from SurfaceFlinger immediately
311     status_t removeLayer(const sp<Layer>& layer);
312
313     // add a layer to SurfaceFlinger
314     status_t addClientLayer(const sp<Client>& client,
315             const sp<IBinder>& handle,
316             const sp<IGraphicBufferProducer>& gbc,
317             const sp<Layer>& lbc);
318
319     /* ------------------------------------------------------------------------
320      * Boot animation, on/off animations and screen capture
321      */
322
323     void startBootAnim();
324
325     void renderScreenImplLocked(
326             const sp<const DisplayDevice>& hw,
327             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
328             uint32_t minLayerZ, uint32_t maxLayerZ,
329             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
330
331     status_t captureScreenImplLocked(
332             const sp<const DisplayDevice>& hw,
333             const sp<IGraphicBufferProducer>& producer,
334             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
335             uint32_t minLayerZ, uint32_t maxLayerZ,
336             bool useIdentityTransform, Transform::orientation_flags rotation,
337             bool isLocalScreenshot);
338
339     /* ------------------------------------------------------------------------
340      * EGL
341      */
342     size_t getMaxTextureSize() const;
343     size_t getMaxViewportDims() const;
344
345     /* ------------------------------------------------------------------------
346      * Display and layer stack management
347      */
348     // called when starting, or restarting after system_server death
349     void initializeDisplays();
350
351     // Create an IBinder for a builtin display and add it to current state
352     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
353
354     // NOTE: can only be called from the main thread or with mStateLock held
355     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
356         return mDisplays.valueFor(dpy);
357     }
358
359     // NOTE: can only be called from the main thread or with mStateLock held
360     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
361         return mDisplays.valueFor(dpy);
362     }
363
364     // mark a region of a layer stack dirty. this updates the dirty
365     // region of all screens presenting this layer stack.
366     void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
367
368 #ifndef USE_HWC2
369     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
370 #endif
371
372     /* ------------------------------------------------------------------------
373      * H/W composer
374      */
375
376     HWComposer& getHwComposer() const { return *mHwc; }
377
378     /* ------------------------------------------------------------------------
379      * Compositing
380      */
381     void invalidateHwcGeometry();
382     static void computeVisibleRegions(
383             const LayerVector& currentLayers, uint32_t layerStack,
384             Region& dirtyRegion, Region& opaqueRegion);
385
386     void preComposition();
387     void postComposition();
388     void rebuildLayerStacks();
389     void setUpHWComposer();
390     void doComposition();
391     void doDebugFlashRegions();
392     void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
393
394     // compose surfaces for display hw. this fails if using GL and the surface
395     // has been destroyed and is no longer valid.
396     bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
397
398     void postFramebuffer();
399     void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
400
401     /* ------------------------------------------------------------------------
402      * Display management
403      */
404
405     /* ------------------------------------------------------------------------
406      * VSync
407      */
408      void enableHardwareVsync();
409      void disableHardwareVsync(bool makeUnavailable);
410      void resyncToHardwareVsync(bool makeAvailable);
411
412     /* ------------------------------------------------------------------------
413      * Debugging & dumpsys
414      */
415     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
416     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
417     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
418     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
419     bool startDdmConnection();
420     static void appendSfConfigString(String8& result);
421     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
422             const sp<const DisplayDevice>& hw,
423             uint32_t minLayerZ, uint32_t maxLayerZ);
424
425     void logFrameStats();
426
427     void dumpStaticScreenStats(String8& result) const;
428
429     /* ------------------------------------------------------------------------
430      * Attributes
431      */
432
433     // access must be protected by mStateLock
434     mutable Mutex mStateLock;
435     State mCurrentState;
436     volatile int32_t mTransactionFlags;
437     Condition mTransactionCV;
438     bool mTransactionPending;
439     bool mAnimTransactionPending;
440     Vector< sp<Layer> > mLayersPendingRemoval;
441     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
442
443     // protected by mStateLock (but we could use another lock)
444     bool mLayersRemoved;
445
446     // access must be protected by mInvalidateLock
447     volatile int32_t mRepaintEverything;
448
449     // constant members (no synchronization needed for access)
450     HWComposer* mHwc;
451     RenderEngine* mRenderEngine;
452     nsecs_t mBootTime;
453     bool mGpuToCpuSupported;
454     bool mDropMissedFrames;
455     sp<EventThread> mEventThread;
456     sp<EventThread> mSFEventThread;
457     sp<EventControlThread> mEventControlThread;
458     EGLContext mEGLContext;
459     EGLDisplay mEGLDisplay;
460     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
461
462     // Can only accessed from the main thread, these members
463     // don't need synchronization
464     State mDrawingState;
465     bool mVisibleRegionsDirty;
466 #ifndef USE_HWC2
467     bool mHwWorkListDirty;
468 #else
469     bool mGeometryInvalid;
470 #endif
471     bool mAnimCompositionPending;
472 #ifdef USE_HWC2
473     std::vector<sp<Layer>> mLayersWithQueuedFrames;
474 #endif
475
476     // this may only be written from the main thread with mStateLock held
477     // it may be read from other threads with mStateLock held
478     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
479
480     // don't use a lock for these, we don't care
481     int mDebugRegion;
482     int mDebugDDMS;
483     int mDebugDisableHWC;
484     int mDebugDisableTransformHint;
485     volatile nsecs_t mDebugInSwapBuffers;
486     nsecs_t mLastSwapBufferTime;
487     volatile nsecs_t mDebugInTransaction;
488     nsecs_t mLastTransactionTime;
489     bool mBootFinished;
490     bool mForceFullDamage;
491
492     // these are thread safe
493     mutable MessageQueue mEventQueue;
494     FrameTracker mAnimFrameTracker;
495     DispSync mPrimaryDispSync;
496
497     // protected by mDestroyedLayerLock;
498     mutable Mutex mDestroyedLayerLock;
499     Vector<Layer const *> mDestroyedLayers;
500
501     // protected by mHWVsyncLock
502     Mutex mHWVsyncLock;
503     bool mPrimaryHWVsyncEnabled;
504     bool mHWVsyncAvailable;
505
506     /* ------------------------------------------------------------------------
507      * Feature prototyping
508      */
509
510     Daltonizer mDaltonizer;
511     bool mDaltonize;
512
513     mat4 mColorMatrix;
514     bool mHasColorMatrix;
515
516     // Static screen stats
517     bool mHasPoweredOff;
518     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
519     nsecs_t mFrameBuckets[NUM_BUCKETS];
520     nsecs_t mTotalTime;
521     nsecs_t mLastSwapTime;
522 };
523
524 }; // namespace android
525
526 #endif // ANDROID_SURFACE_FLINGER_H