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