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 #include "RenderProxy.h"
18 
19 #include "DeferredLayerUpdater.h"
20 #include "DisplayList.h"
21 #include "Properties.h"
22 #include "Readback.h"
23 #include "Rect.h"
24 #include "WebViewFunctorManager.h"
25 #include "renderthread/CanvasContext.h"
26 #include "renderthread/RenderTask.h"
27 #include "renderthread/RenderThread.h"
28 #include "utils/Macros.h"
29 #include "utils/TimeUtils.h"
30 #include "utils/TraceUtils.h"
31 
32 namespace android {
33 namespace uirenderer {
34 namespace renderthread {
35 
RenderProxy(bool translucent,RenderNode * rootRenderNode,IContextFactory * contextFactory)36 RenderProxy::RenderProxy(bool translucent, RenderNode* rootRenderNode,
37                          IContextFactory* contextFactory)
38         : mRenderThread(RenderThread::getInstance()), mContext(nullptr) {
39     mContext = mRenderThread.queue().runSync([&]() -> CanvasContext* {
40         return CanvasContext::create(mRenderThread, translucent, rootRenderNode, contextFactory);
41     });
42     mDrawFrameTask.setContext(&mRenderThread, mContext, rootRenderNode);
43 }
44 
~RenderProxy()45 RenderProxy::~RenderProxy() {
46     destroyContext();
47 }
48 
destroyContext()49 void RenderProxy::destroyContext() {
50     if (mContext) {
51         mDrawFrameTask.setContext(nullptr, nullptr, nullptr);
52         // This is also a fence as we need to be certain that there are no
53         // outstanding mDrawFrame tasks posted before it is destroyed
54         mRenderThread.queue().runSync([this]() { delete mContext; });
55         mContext = nullptr;
56     }
57 }
58 
setSwapBehavior(SwapBehavior swapBehavior)59 void RenderProxy::setSwapBehavior(SwapBehavior swapBehavior) {
60     mRenderThread.queue().post([this, swapBehavior]() { mContext->setSwapBehavior(swapBehavior); });
61 }
62 
loadSystemProperties()63 bool RenderProxy::loadSystemProperties() {
64     return mRenderThread.queue().runSync([this]() -> bool {
65         bool needsRedraw = Properties::load();
66         if (mContext->profiler().consumeProperties()) {
67             needsRedraw = true;
68         }
69         return needsRedraw;
70     });
71 }
72 
setName(const char * name)73 void RenderProxy::setName(const char* name) {
74     // block since name/value pointers owned by caller
75     // TODO: Support move arguments
76     mRenderThread.queue().runSync([this, name]() { mContext->setName(std::string(name)); });
77 }
78 
setSurface(ANativeWindow * window,bool enableTimeout)79 void RenderProxy::setSurface(ANativeWindow* window, bool enableTimeout) {
80     ANativeWindow_acquire(window);
81     mRenderThread.queue().post([this, win = window, enableTimeout]() mutable {
82         mContext->setSurface(win, enableTimeout);
83         ANativeWindow_release(win);
84     });
85 }
86 
allocateBuffers()87 void RenderProxy::allocateBuffers() {
88     mRenderThread.queue().post([=]() { mContext->allocateBuffers(); });
89 }
90 
pause()91 bool RenderProxy::pause() {
92     return mRenderThread.queue().runSync([this]() -> bool { return mContext->pauseSurface(); });
93 }
94 
setStopped(bool stopped)95 void RenderProxy::setStopped(bool stopped) {
96     mRenderThread.queue().runSync([this, stopped]() { mContext->setStopped(stopped); });
97 }
98 
setLightAlpha(uint8_t ambientShadowAlpha,uint8_t spotShadowAlpha)99 void RenderProxy::setLightAlpha(uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
100     mRenderThread.queue().post(
101             [=]() { mContext->setLightAlpha(ambientShadowAlpha, spotShadowAlpha); });
102 }
103 
setLightGeometry(const Vector3 & lightCenter,float lightRadius)104 void RenderProxy::setLightGeometry(const Vector3& lightCenter, float lightRadius) {
105     mRenderThread.queue().post([=]() { mContext->setLightGeometry(lightCenter, lightRadius); });
106 }
107 
setOpaque(bool opaque)108 void RenderProxy::setOpaque(bool opaque) {
109     mRenderThread.queue().post([=]() { mContext->setOpaque(opaque); });
110 }
111 
setWideGamut(bool wideGamut)112 void RenderProxy::setWideGamut(bool wideGamut) {
113     mRenderThread.queue().post([=]() { mContext->setWideGamut(wideGamut); });
114 }
115 
frameInfo()116 int64_t* RenderProxy::frameInfo() {
117     return mDrawFrameTask.frameInfo();
118 }
119 
syncAndDrawFrame()120 int RenderProxy::syncAndDrawFrame() {
121     return mDrawFrameTask.drawFrame();
122 }
123 
destroy()124 void RenderProxy::destroy() {
125     // destroyCanvasAndSurface() needs a fence as when it returns the
126     // underlying BufferQueue is going to be released from under
127     // the render thread.
128     mRenderThread.queue().runSync([=]() { mContext->destroy(); });
129 }
130 
invokeFunctor(Functor * functor,bool waitForCompletion)131 void RenderProxy::invokeFunctor(Functor* functor, bool waitForCompletion) {
132     ATRACE_CALL();
133     RenderThread& thread = RenderThread::getInstance();
134     auto invoke = [&thread, functor]() { CanvasContext::invokeFunctor(thread, functor); };
135     if (waitForCompletion) {
136         // waitForCompletion = true is expected to be fairly rare and only
137         // happen in destruction. Thus it should be fine to temporarily
138         // create a Mutex
139         thread.queue().runSync(std::move(invoke));
140     } else {
141         thread.queue().post(std::move(invoke));
142     }
143 }
144 
destroyFunctor(int functor)145 void RenderProxy::destroyFunctor(int functor) {
146     ATRACE_CALL();
147     RenderThread& thread = RenderThread::getInstance();
148     thread.queue().post([=]() { WebViewFunctorManager::instance().destroyFunctor(functor); });
149 }
150 
createTextureLayer()151 DeferredLayerUpdater* RenderProxy::createTextureLayer() {
152     return mRenderThread.queue().runSync([this]() -> auto {
153         return mContext->createTextureLayer();
154     });
155 }
156 
buildLayer(RenderNode * node)157 void RenderProxy::buildLayer(RenderNode* node) {
158     mRenderThread.queue().runSync([&]() { mContext->buildLayer(node); });
159 }
160 
copyLayerInto(DeferredLayerUpdater * layer,SkBitmap & bitmap)161 bool RenderProxy::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap& bitmap) {
162     ATRACE_NAME("TextureView#getBitmap");
163     auto& thread = RenderThread::getInstance();
164     return thread.queue().runSync([&]() -> bool {
165         return thread.readback().copyLayerInto(layer, &bitmap) == CopyResult::Success;
166     });
167 }
168 
pushLayerUpdate(DeferredLayerUpdater * layer)169 void RenderProxy::pushLayerUpdate(DeferredLayerUpdater* layer) {
170     mDrawFrameTask.pushLayerUpdate(layer);
171 }
172 
cancelLayerUpdate(DeferredLayerUpdater * layer)173 void RenderProxy::cancelLayerUpdate(DeferredLayerUpdater* layer) {
174     mDrawFrameTask.removeLayerUpdate(layer);
175 }
176 
detachSurfaceTexture(DeferredLayerUpdater * layer)177 void RenderProxy::detachSurfaceTexture(DeferredLayerUpdater* layer) {
178     return mRenderThread.queue().runSync([&]() { layer->detachSurfaceTexture(); });
179 }
180 
destroyHardwareResources()181 void RenderProxy::destroyHardwareResources() {
182     return mRenderThread.queue().runSync([&]() { mContext->destroyHardwareResources(); });
183 }
184 
trimMemory(int level)185 void RenderProxy::trimMemory(int level) {
186     // Avoid creating a RenderThread to do a trimMemory.
187     if (RenderThread::hasInstance()) {
188         RenderThread& thread = RenderThread::getInstance();
189         thread.queue().post([&thread, level]() { CanvasContext::trimMemory(thread, level); });
190     }
191 }
192 
overrideProperty(const char * name,const char * value)193 void RenderProxy::overrideProperty(const char* name, const char* value) {
194     // expensive, but block here since name/value pointers owned by caller
195     RenderThread::getInstance().queue().runSync(
196             [&]() { Properties::overrideProperty(name, value); });
197 }
198 
fence()199 void RenderProxy::fence() {
200     mRenderThread.queue().runSync([]() {});
201 }
202 
maxTextureSize()203 int RenderProxy::maxTextureSize() {
204     static int maxTextureSize = RenderThread::getInstance().queue().runSync(
205             []() { return DeviceInfo::get()->maxTextureSize(); });
206     return maxTextureSize;
207 }
208 
stopDrawing()209 void RenderProxy::stopDrawing() {
210     mRenderThread.queue().runSync([this]() { mContext->stopDrawing(); });
211 }
212 
notifyFramePending()213 void RenderProxy::notifyFramePending() {
214     mRenderThread.queue().post([this]() { mContext->notifyFramePending(); });
215 }
216 
dumpProfileInfo(int fd,int dumpFlags)217 void RenderProxy::dumpProfileInfo(int fd, int dumpFlags) {
218     mRenderThread.queue().runSync([&]() {
219         mContext->profiler().dumpData(fd);
220         if (dumpFlags & DumpFlags::FrameStats) {
221             mContext->dumpFrames(fd);
222         }
223         if (dumpFlags & DumpFlags::JankStats) {
224             mRenderThread.globalProfileData()->dump(fd);
225         }
226         if (dumpFlags & DumpFlags::Reset) {
227             mContext->resetFrameStats();
228         }
229     });
230 }
231 
resetProfileInfo()232 void RenderProxy::resetProfileInfo() {
233     mRenderThread.queue().runSync([=]() { mContext->resetFrameStats(); });
234 }
235 
frameTimePercentile(int percentile)236 uint32_t RenderProxy::frameTimePercentile(int percentile) {
237     return mRenderThread.queue().runSync([&]() -> auto {
238         return mRenderThread.globalProfileData()->findPercentile(percentile);
239     });
240 }
241 
dumpGraphicsMemory(int fd)242 void RenderProxy::dumpGraphicsMemory(int fd) {
243     if (RenderThread::hasInstance()) {
244         auto& thread = RenderThread::getInstance();
245         thread.queue().runSync([&]() { thread.dumpGraphicsMemory(fd); });
246     }
247 }
248 
setProcessStatsBuffer(int fd)249 void RenderProxy::setProcessStatsBuffer(int fd) {
250     auto& rt = RenderThread::getInstance();
251     rt.queue().post([&rt, fd = dup(fd)]() {
252         rt.globalProfileData().switchStorageToAshmem(fd);
253         close(fd);
254     });
255 }
256 
rotateProcessStatsBuffer()257 void RenderProxy::rotateProcessStatsBuffer() {
258     auto& rt = RenderThread::getInstance();
259     rt.queue().post([&rt]() { rt.globalProfileData().rotateStorage(); });
260 }
261 
getRenderThreadTid()262 int RenderProxy::getRenderThreadTid() {
263     return mRenderThread.getTid();
264 }
265 
addRenderNode(RenderNode * node,bool placeFront)266 void RenderProxy::addRenderNode(RenderNode* node, bool placeFront) {
267     mRenderThread.queue().post([=]() { mContext->addRenderNode(node, placeFront); });
268 }
269 
removeRenderNode(RenderNode * node)270 void RenderProxy::removeRenderNode(RenderNode* node) {
271     mRenderThread.queue().post([=]() { mContext->removeRenderNode(node); });
272 }
273 
drawRenderNode(RenderNode * node)274 void RenderProxy::drawRenderNode(RenderNode* node) {
275     mRenderThread.queue().runSync([=]() { mContext->prepareAndDraw(node); });
276 }
277 
setContentDrawBounds(int left,int top,int right,int bottom)278 void RenderProxy::setContentDrawBounds(int left, int top, int right, int bottom) {
279     mDrawFrameTask.setContentDrawBounds(left, top, right, bottom);
280 }
281 
setPictureCapturedCallback(const std::function<void (sk_sp<SkPicture> &&)> & callback)282 void RenderProxy::setPictureCapturedCallback(
283         const std::function<void(sk_sp<SkPicture>&&)>& callback) {
284     mRenderThread.queue().post(
285             [this, cb = callback]() { mContext->setPictureCapturedCallback(cb); });
286 }
287 
setFrameCallback(std::function<void (int64_t)> && callback)288 void RenderProxy::setFrameCallback(std::function<void(int64_t)>&& callback) {
289     mDrawFrameTask.setFrameCallback(std::move(callback));
290 }
291 
setFrameCompleteCallback(std::function<void (int64_t)> && callback)292 void RenderProxy::setFrameCompleteCallback(std::function<void(int64_t)>&& callback) {
293     mDrawFrameTask.setFrameCompleteCallback(std::move(callback));
294 }
295 
addFrameMetricsObserver(FrameMetricsObserver * observerPtr)296 void RenderProxy::addFrameMetricsObserver(FrameMetricsObserver* observerPtr) {
297     mRenderThread.queue().post([this, observer = sp{observerPtr}]() {
298         mContext->addFrameMetricsObserver(observer.get());
299     });
300 }
301 
removeFrameMetricsObserver(FrameMetricsObserver * observerPtr)302 void RenderProxy::removeFrameMetricsObserver(FrameMetricsObserver* observerPtr) {
303     mRenderThread.queue().post([this, observer = sp{observerPtr}]() {
304         mContext->removeFrameMetricsObserver(observer.get());
305     });
306 }
307 
setForceDark(bool enable)308 void RenderProxy::setForceDark(bool enable) {
309     mRenderThread.queue().post([this, enable]() { mContext->setForceDark(enable); });
310 }
311 
setRenderAheadDepth(int renderAhead)312 void RenderProxy::setRenderAheadDepth(int renderAhead) {
313     mRenderThread.queue().post(
314             [context = mContext, renderAhead] { context->setRenderAheadDepth(renderAhead); });
315 }
316 
copySurfaceInto(ANativeWindow * window,int left,int top,int right,int bottom,SkBitmap * bitmap)317 int RenderProxy::copySurfaceInto(ANativeWindow* window, int left, int top, int right, int bottom,
318                                  SkBitmap* bitmap) {
319     auto& thread = RenderThread::getInstance();
320     return static_cast<int>(thread.queue().runSync([&]() -> auto {
321         return thread.readback().copySurfaceInto(window, Rect(left, top, right, bottom), bitmap);
322     }));
323 }
324 
prepareToDraw(Bitmap & bitmap)325 void RenderProxy::prepareToDraw(Bitmap& bitmap) {
326     // If we haven't spun up a hardware accelerated window yet, there's no
327     // point in precaching these bitmaps as it can't impact jank.
328     // We also don't know if we even will spin up a hardware-accelerated
329     // window or not.
330     if (!RenderThread::hasInstance()) return;
331     RenderThread* renderThread = &RenderThread::getInstance();
332     bitmap.ref();
333     auto task = [renderThread, &bitmap]() {
334         CanvasContext::prepareToDraw(*renderThread, &bitmap);
335         bitmap.unref();
336     };
337     nsecs_t lastVsync = renderThread->timeLord().latestVsync();
338     nsecs_t estimatedNextVsync = lastVsync + renderThread->timeLord().frameIntervalNanos();
339     nsecs_t timeToNextVsync = estimatedNextVsync - systemTime(SYSTEM_TIME_MONOTONIC);
340     // We expect the UI thread to take 4ms and for RT to be active from VSYNC+4ms to
341     // VSYNC+12ms or so, so aim for the gap during which RT is expected to
342     // be idle
343     // TODO: Make this concept a first-class supported thing? RT could use
344     // knowledge of pending draws to better schedule this task
345     if (timeToNextVsync > -6_ms && timeToNextVsync < 1_ms) {
346         renderThread->queue().postAt(estimatedNextVsync + 8_ms, task);
347     } else {
348         renderThread->queue().post(task);
349     }
350 }
351 
copyHWBitmapInto(Bitmap * hwBitmap,SkBitmap * bitmap)352 int RenderProxy::copyHWBitmapInto(Bitmap* hwBitmap, SkBitmap* bitmap) {
353     ATRACE_NAME("HardwareBitmap readback");
354     RenderThread& thread = RenderThread::getInstance();
355     if (gettid() == thread.getTid()) {
356         // TODO: fix everything that hits this. We should never be triggering a readback ourselves.
357         return (int)thread.readback().copyHWBitmapInto(hwBitmap, bitmap);
358     } else {
359         return thread.queue().runSync(
360                 [&]() -> int { return (int)thread.readback().copyHWBitmapInto(hwBitmap, bitmap); });
361     }
362 }
363 
disableVsync()364 void RenderProxy::disableVsync() {
365     Properties::disableVsync = true;
366 }
367 
preload()368 void RenderProxy::preload() {
369     // Create RenderThread object and start the thread. Then preload Vulkan/EGL driver.
370     auto& thread = RenderThread::getInstance();
371     thread.queue().post([&thread]() { thread.preload(); });
372 }
373 
374 } /* namespace renderthread */
375 } /* namespace uirenderer */
376 } /* namespace android */
377