1 /*
2  * Copyright (C) 2013 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 RENDERTHREAD_H_
18 #define RENDERTHREAD_H_
19 
20 #include <GrDirectContext.h>
21 #include <SkBitmap.h>
22 #include <cutils/compiler.h>
23 #include <surface_control_private.h>
24 #include <utils/Thread.h>
25 
26 #include <memory>
27 #include <mutex>
28 #include <set>
29 
30 #include "CacheManager.h"
31 #include "MemoryPolicy.h"
32 #include "ProfileDataContainer.h"
33 #include "RenderTask.h"
34 #include "TimeLord.h"
35 #include "WebViewFunctorManager.h"
36 #include "thread/ThreadBase.h"
37 #include "utils/TimeUtils.h"
38 
39 namespace android {
40 
41 class Bitmap;
42 
43 namespace uirenderer {
44 
45 class AutoBackendTextureRelease;
46 class Readback;
47 class RenderState;
48 class TestUtils;
49 
50 namespace skiapipeline {
51 class VkFunctorDrawHandler;
52 }
53 
54 namespace VectorDrawable {
55 class Tree;
56 }
57 
58 namespace renderthread {
59 
60 class CanvasContext;
61 class EglManager;
62 class RenderProxy;
63 class VulkanManager;
64 
65 // Mimics android.view.Choreographer.FrameCallback
66 class IFrameCallback {
67 public:
68     virtual void doFrame() = 0;
69 
70 protected:
~IFrameCallback()71     virtual ~IFrameCallback() {}
72 };
73 
74 struct VsyncSource {
75     virtual void requestNextVsync() = 0;
76     virtual void drainPendingEvents() = 0;
~VsyncSourceVsyncSource77     virtual ~VsyncSource() {}
78 };
79 
80 typedef ASurfaceControl* (*ASC_create)(ASurfaceControl* parent, const char* debug_name);
81 typedef void (*ASC_acquire)(ASurfaceControl* control);
82 typedef void (*ASC_release)(ASurfaceControl* control);
83 
84 typedef void (*ASC_registerSurfaceStatsListener)(ASurfaceControl* control, int32_t id,
85                                                  void* context,
86                                                  ASurfaceControl_SurfaceStatsListener func);
87 typedef void (*ASC_unregisterSurfaceStatsListener)(void* context,
88                                                    ASurfaceControl_SurfaceStatsListener func);
89 
90 typedef int64_t (*ASCStats_getAcquireTime)(ASurfaceControlStats* stats);
91 typedef uint64_t (*ASCStats_getFrameNumber)(ASurfaceControlStats* stats);
92 
93 typedef ASurfaceTransaction* (*AST_create)();
94 typedef void (*AST_delete)(ASurfaceTransaction* transaction);
95 typedef void (*AST_apply)(ASurfaceTransaction* transaction);
96 typedef void (*AST_reparent)(ASurfaceTransaction* aSurfaceTransaction,
97                              ASurfaceControl* aSurfaceControl,
98                              ASurfaceControl* newParentASurfaceControl);
99 typedef void (*AST_setVisibility)(ASurfaceTransaction* transaction,
100                                   ASurfaceControl* surface_control, int8_t visibility);
101 typedef void (*AST_setZOrder)(ASurfaceTransaction* transaction, ASurfaceControl* surface_control,
102                               int32_t z_order);
103 
104 struct ASurfaceControlFunctions {
105     ASurfaceControlFunctions();
106 
107     ASC_create createFunc;
108     ASC_acquire acquireFunc;
109     ASC_release releaseFunc;
110     ASC_registerSurfaceStatsListener registerListenerFunc;
111     ASC_unregisterSurfaceStatsListener unregisterListenerFunc;
112     ASCStats_getAcquireTime getAcquireTimeFunc;
113     ASCStats_getFrameNumber getFrameNumberFunc;
114 
115     AST_create transactionCreateFunc;
116     AST_delete transactionDeleteFunc;
117     AST_apply transactionApplyFunc;
118     AST_reparent transactionReparentFunc;
119     AST_setVisibility transactionSetVisibilityFunc;
120     AST_setZOrder transactionSetZOrderFunc;
121 };
122 
123 class ChoreographerSource;
124 class DummyVsyncSource;
125 
126 typedef void (*JVMAttachHook)(const char* name);
127 
128 class RenderThread : private ThreadBase {
129     PREVENT_COPY_AND_ASSIGN(RenderThread);
130 
131 public:
132     // Sets a callback that fires before any RenderThread setup has occurred.
133     static void setOnStartHook(JVMAttachHook onStartHook);
134     static JVMAttachHook getOnStartHook();
135 
queue()136     WorkQueue& queue() { return ThreadBase::queue(); }
137 
138     // Mimics android.view.Choreographer
139     void postFrameCallback(IFrameCallback* callback);
140     bool removeFrameCallback(IFrameCallback* callback);
141     // If the callback is currently registered, it will be pushed back until
142     // the next vsync. If it is not currently registered this does nothing.
143     void pushBackFrameCallback(IFrameCallback* callback);
144 
timeLord()145     TimeLord& timeLord() { return mTimeLord; }
renderState()146     RenderState& renderState() const { return *mRenderState; }
eglManager()147     EglManager& eglManager() const { return *mEglManager; }
globalProfileData()148     ProfileDataContainer& globalProfileData() { return mGlobalProfileData; }
getJankDataMutex()149     std::mutex& getJankDataMutex() { return mJankDataMutex; }
150     Readback& readback();
151 
getGrContext()152     GrDirectContext* getGrContext() const { return mGrContext.get(); }
153     void setGrContext(sk_sp<GrDirectContext> cxt);
154     sk_sp<GrDirectContext> requireGrContext();
155 
cacheManager()156     CacheManager& cacheManager() { return *mCacheManager; }
157     VulkanManager& vulkanManager();
158 
159     sk_sp<Bitmap> allocateHardwareBitmap(SkBitmap& skBitmap);
160     void dumpGraphicsMemory(int fd, bool includeProfileData);
161     void getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage);
162 
163     void requireGlContext();
164     void requireVkContext();
165     void destroyRenderingContext();
166 
167     void preload();
168 
getASurfaceControlFunctions()169     const ASurfaceControlFunctions& getASurfaceControlFunctions() {
170         return mASurfaceControlFunctions;
171     }
172 
173     void trimMemory(TrimLevel level);
174     void trimCaches(CacheTrimLevel level);
175 
176     /**
177      * isCurrent provides a way to query, if the caller is running on
178      * the render thread.
179      *
180      * @return true only if isCurrent is invoked from the render thread.
181      */
182     static bool isCurrent();
183 
184     static void initGrContextOptions(GrContextOptions& options);
185 
186 protected:
187     virtual bool threadLoop() override;
188 
189 private:
190     friend class DispatchFrameCallbacks;
191     friend class RenderProxy;
192     friend class DummyVsyncSource;
193     friend class ChoreographerSource;
194     friend class android::uirenderer::AutoBackendTextureRelease;
195     friend class android::uirenderer::TestUtils;
196     friend class android::uirenderer::WebViewFunctor;
197     friend class android::uirenderer::skiapipeline::VkFunctorDrawHandler;
198     friend class android::uirenderer::VectorDrawable::Tree;
199     friend class sp<RenderThread>;
200 
201     RenderThread();
202     virtual ~RenderThread();
203 
204     static bool hasInstance();
205     static RenderThread& getInstance();
206 
207     void initThreadLocals();
208     void initializeChoreographer();
209     void setupFrameInterval();
210     // Callbacks for choreographer events:
211     // choreographerCallback will call AChoreograper_handleEvent to call the
212     // corresponding callbacks for each display event type
213     static int choreographerCallback(int fd, int events, void* data);
214     // Callback that will be run on vsync ticks.
215     static void extendedFrameCallback(const AChoreographerFrameCallbackData* cbData, void* data);
216     void frameCallback(int64_t vsyncId, int64_t frameDeadline, int64_t frameTimeNanos,
217                        int64_t frameInterval);
218     // Callback that will be run whenver there is a refresh rate change.
219     static void refreshRateCallback(int64_t vsyncPeriod, void* data);
220     void drainDisplayEventQueue();
221     void dispatchFrameCallbacks();
222     void requestVsync();
223 
224     AChoreographer* mChoreographer;
225     VsyncSource* mVsyncSource;
226     bool mVsyncRequested;
227     std::set<IFrameCallback*> mFrameCallbacks;
228     // We defer the actual registration of these callbacks until
229     // both mQueue *and* mDisplayEventReceiver have been drained off all
230     // immediate events. This makes sure that we catch the next vsync, not
231     // the previous one
232     std::set<IFrameCallback*> mPendingRegistrationFrameCallbacks;
233     bool mFrameCallbackTaskPending;
234 
235     TimeLord mTimeLord;
236     RenderState* mRenderState;
237     EglManager* mEglManager;
238     WebViewFunctorManager& mFunctorManager;
239 
240     ProfileDataContainer mGlobalProfileData;
241     Readback* mReadback = nullptr;
242 
243     sk_sp<GrDirectContext> mGrContext;
244     CacheManager* mCacheManager;
245     sp<VulkanManager> mVkManager;
246 
247     ASurfaceControlFunctions mASurfaceControlFunctions;
248     std::mutex mJankDataMutex;
249 };
250 
251 } /* namespace renderthread */
252 } /* namespace uirenderer */
253 } /* namespace android */
254 #endif /* RENDERTHREAD_H_ */
255