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