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 "RenderThread.h"
18
19 #include <gui/TraceUtils.h>
20 #include "../HardwareBitmapUploader.h"
21 #include "CanvasContext.h"
22 #include "DeviceInfo.h"
23 #include "EglManager.h"
24 #include "Properties.h"
25 #include "Readback.h"
26 #include "RenderProxy.h"
27 #include "VulkanManager.h"
28 #include "hwui/Bitmap.h"
29 #include "pipeline/skia/SkiaOpenGLPipeline.h"
30 #include "pipeline/skia/SkiaVulkanPipeline.h"
31 #include "renderstate/RenderState.h"
32 #include "utils/TimeUtils.h"
33
34 #include <GrContextOptions.h>
35 #include <gl/GrGLInterface.h>
36
37 #include <dlfcn.h>
38 #include <sys/resource.h>
39 #include <utils/Condition.h>
40 #include <utils/Log.h>
41 #include <utils/Mutex.h>
42 #include <thread>
43
44 #include <android-base/properties.h>
45 #include <ui/FatVector.h>
46
47 namespace android {
48 namespace uirenderer {
49 namespace renderthread {
50
51 static bool gHasRenderThreadInstance = false;
52
53 static JVMAttachHook gOnStartHook = nullptr;
54
ASurfaceControlFunctions()55 ASurfaceControlFunctions::ASurfaceControlFunctions() {
56 void* handle_ = dlopen("libandroid.so", RTLD_NOW | RTLD_NODELETE);
57 createFunc = (ASC_create)dlsym(handle_, "ASurfaceControl_create");
58 LOG_ALWAYS_FATAL_IF(createFunc == nullptr,
59 "Failed to find required symbol ASurfaceControl_create!");
60
61 acquireFunc = (ASC_acquire) dlsym(handle_, "ASurfaceControl_acquire");
62 LOG_ALWAYS_FATAL_IF(acquireFunc == nullptr,
63 "Failed to find required symbol ASurfaceControl_acquire!");
64
65 releaseFunc = (ASC_release) dlsym(handle_, "ASurfaceControl_release");
66 LOG_ALWAYS_FATAL_IF(releaseFunc == nullptr,
67 "Failed to find required symbol ASurfaceControl_release!");
68
69 registerListenerFunc = (ASC_registerSurfaceStatsListener) dlsym(handle_,
70 "ASurfaceControl_registerSurfaceStatsListener");
71 LOG_ALWAYS_FATAL_IF(registerListenerFunc == nullptr,
72 "Failed to find required symbol ASurfaceControl_registerSurfaceStatsListener!");
73
74 unregisterListenerFunc = (ASC_unregisterSurfaceStatsListener) dlsym(handle_,
75 "ASurfaceControl_unregisterSurfaceStatsListener");
76 LOG_ALWAYS_FATAL_IF(unregisterListenerFunc == nullptr,
77 "Failed to find required symbol ASurfaceControl_unregisterSurfaceStatsListener!");
78
79 getAcquireTimeFunc = (ASCStats_getAcquireTime) dlsym(handle_,
80 "ASurfaceControlStats_getAcquireTime");
81 LOG_ALWAYS_FATAL_IF(getAcquireTimeFunc == nullptr,
82 "Failed to find required symbol ASurfaceControlStats_getAcquireTime!");
83
84 getFrameNumberFunc = (ASCStats_getFrameNumber) dlsym(handle_,
85 "ASurfaceControlStats_getFrameNumber");
86 LOG_ALWAYS_FATAL_IF(getFrameNumberFunc == nullptr,
87 "Failed to find required symbol ASurfaceControlStats_getFrameNumber!");
88
89 transactionCreateFunc = (AST_create)dlsym(handle_, "ASurfaceTransaction_create");
90 LOG_ALWAYS_FATAL_IF(transactionCreateFunc == nullptr,
91 "Failed to find required symbol ASurfaceTransaction_create!");
92
93 transactionDeleteFunc = (AST_delete)dlsym(handle_, "ASurfaceTransaction_delete");
94 LOG_ALWAYS_FATAL_IF(transactionDeleteFunc == nullptr,
95 "Failed to find required symbol ASurfaceTransaction_delete!");
96
97 transactionApplyFunc = (AST_apply)dlsym(handle_, "ASurfaceTransaction_apply");
98 LOG_ALWAYS_FATAL_IF(transactionApplyFunc == nullptr,
99 "Failed to find required symbol ASurfaceTransaction_apply!");
100
101 transactionReparentFunc = (AST_reparent)dlsym(handle_, "ASurfaceTransaction_reparent");
102 LOG_ALWAYS_FATAL_IF(transactionReparentFunc == nullptr,
103 "Failed to find required symbol transactionReparentFunc!");
104
105 transactionSetVisibilityFunc =
106 (AST_setVisibility)dlsym(handle_, "ASurfaceTransaction_setVisibility");
107 LOG_ALWAYS_FATAL_IF(transactionSetVisibilityFunc == nullptr,
108 "Failed to find required symbol ASurfaceTransaction_setVisibility!");
109
110 transactionSetZOrderFunc = (AST_setZOrder)dlsym(handle_, "ASurfaceTransaction_setZOrder");
111 LOG_ALWAYS_FATAL_IF(transactionSetZOrderFunc == nullptr,
112 "Failed to find required symbol ASurfaceTransaction_setZOrder!");
113 }
114
frameCallback(int64_t frameTimeNanos,void * data)115 void RenderThread::frameCallback(int64_t frameTimeNanos, void* data) {
116 RenderThread* rt = reinterpret_cast<RenderThread*>(data);
117 int64_t vsyncId = AChoreographer_getVsyncId(rt->mChoreographer);
118 int64_t frameDeadline = AChoreographer_getFrameDeadline(rt->mChoreographer);
119 int64_t frameInterval = AChoreographer_getFrameInterval(rt->mChoreographer);
120 rt->mVsyncRequested = false;
121 if (rt->timeLord().vsyncReceived(frameTimeNanos, frameTimeNanos, vsyncId, frameDeadline,
122 frameInterval) && !rt->mFrameCallbackTaskPending) {
123 ATRACE_NAME("queue mFrameCallbackTask");
124 rt->mFrameCallbackTaskPending = true;
125 nsecs_t runAt = (frameTimeNanos + rt->mDispatchFrameDelay);
126 rt->queue().postAt(runAt, [=]() { rt->dispatchFrameCallbacks(); });
127 }
128 }
129
refreshRateCallback(int64_t vsyncPeriod,void * data)130 void RenderThread::refreshRateCallback(int64_t vsyncPeriod, void* data) {
131 ATRACE_NAME("refreshRateCallback");
132 RenderThread* rt = reinterpret_cast<RenderThread*>(data);
133 DeviceInfo::get()->onRefreshRateChanged(vsyncPeriod);
134 rt->setupFrameInterval();
135 }
136
137 class ChoreographerSource : public VsyncSource {
138 public:
ChoreographerSource(RenderThread * renderThread)139 ChoreographerSource(RenderThread* renderThread) : mRenderThread(renderThread) {}
140
requestNextVsync()141 virtual void requestNextVsync() override {
142 AChoreographer_postFrameCallback64(mRenderThread->mChoreographer,
143 RenderThread::frameCallback, mRenderThread);
144 }
145
drainPendingEvents()146 virtual void drainPendingEvents() override {
147 AChoreographer_handlePendingEvents(mRenderThread->mChoreographer, mRenderThread);
148 }
149
150 private:
151 RenderThread* mRenderThread;
152 };
153
154 class DummyVsyncSource : public VsyncSource {
155 public:
DummyVsyncSource(RenderThread * renderThread)156 DummyVsyncSource(RenderThread* renderThread) : mRenderThread(renderThread) {}
157
requestNextVsync()158 virtual void requestNextVsync() override {
159 mRenderThread->queue().postDelayed(16_ms, [this]() {
160 RenderThread::frameCallback(systemTime(SYSTEM_TIME_MONOTONIC), mRenderThread);
161 });
162 }
163
drainPendingEvents()164 virtual void drainPendingEvents() override {
165 RenderThread::frameCallback(systemTime(SYSTEM_TIME_MONOTONIC), mRenderThread);
166 }
167
168 private:
169 RenderThread* mRenderThread;
170 };
171
hasInstance()172 bool RenderThread::hasInstance() {
173 return gHasRenderThreadInstance;
174 }
175
setOnStartHook(JVMAttachHook onStartHook)176 void RenderThread::setOnStartHook(JVMAttachHook onStartHook) {
177 LOG_ALWAYS_FATAL_IF(hasInstance(), "can't set an onStartHook after we've started...");
178 gOnStartHook = onStartHook;
179 }
180
getOnStartHook()181 JVMAttachHook RenderThread::getOnStartHook() {
182 return gOnStartHook;
183 }
184
getInstance()185 RenderThread& RenderThread::getInstance() {
186 [[clang::no_destroy]] static sp<RenderThread> sInstance = []() {
187 sp<RenderThread> thread = sp<RenderThread>::make();
188 thread->start("RenderThread");
189 return thread;
190 }();
191 gHasRenderThreadInstance = true;
192 return *sInstance;
193 }
194
RenderThread()195 RenderThread::RenderThread()
196 : ThreadBase()
197 , mVsyncSource(nullptr)
198 , mVsyncRequested(false)
199 , mFrameCallbackTaskPending(false)
200 , mRenderState(nullptr)
201 , mEglManager(nullptr)
202 , mFunctorManager(WebViewFunctorManager::instance())
203 , mGlobalProfileData(mJankDataMutex) {
204 Properties::load();
205 }
206
~RenderThread()207 RenderThread::~RenderThread() {
208 // Note that if this fatal assertion is removed then member variables must
209 // be properly destroyed.
210 LOG_ALWAYS_FATAL("Can't destroy the render thread");
211 }
212
initializeChoreographer()213 void RenderThread::initializeChoreographer() {
214 LOG_ALWAYS_FATAL_IF(mVsyncSource, "Initializing a second Choreographer?");
215
216 if (!Properties::isolatedProcess) {
217 mChoreographer = AChoreographer_create();
218 LOG_ALWAYS_FATAL_IF(mChoreographer == nullptr, "Initialization of Choreographer failed");
219 AChoreographer_registerRefreshRateCallback(mChoreographer,
220 RenderThread::refreshRateCallback, this);
221
222 // Register the FD
223 mLooper->addFd(AChoreographer_getFd(mChoreographer), 0, Looper::EVENT_INPUT,
224 RenderThread::choreographerCallback, this);
225 mVsyncSource = new ChoreographerSource(this);
226 } else {
227 mVsyncSource = new DummyVsyncSource(this);
228 }
229 }
230
initThreadLocals()231 void RenderThread::initThreadLocals() {
232 setupFrameInterval();
233 initializeChoreographer();
234 mEglManager = new EglManager();
235 mRenderState = new RenderState(*this);
236 mVkManager = VulkanManager::getInstance();
237 mCacheManager = new CacheManager();
238 }
239
setupFrameInterval()240 void RenderThread::setupFrameInterval() {
241 nsecs_t frameIntervalNanos = DeviceInfo::getVsyncPeriod();
242 mTimeLord.setFrameInterval(frameIntervalNanos);
243 mDispatchFrameDelay = static_cast<nsecs_t>(frameIntervalNanos * .25f);
244 }
245
requireGlContext()246 void RenderThread::requireGlContext() {
247 if (mEglManager->hasEglContext()) {
248 return;
249 }
250 mEglManager->initialize();
251
252 sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
253 LOG_ALWAYS_FATAL_IF(!glInterface.get());
254
255 GrContextOptions options;
256 initGrContextOptions(options);
257 auto glesVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
258 auto size = glesVersion ? strlen(glesVersion) : -1;
259 cacheManager().configureContext(&options, glesVersion, size);
260 sk_sp<GrDirectContext> grContext(GrDirectContext::MakeGL(std::move(glInterface), options));
261 LOG_ALWAYS_FATAL_IF(!grContext.get());
262 setGrContext(grContext);
263 }
264
requireVkContext()265 void RenderThread::requireVkContext() {
266 // the getter creates the context in the event it had been destroyed by destroyRenderingContext
267 // Also check if we have a GrContext before returning fast. VulkanManager may be shared with
268 // the HardwareBitmapUploader which initializes the Vk context without persisting the GrContext
269 // in the rendering thread.
270 if (vulkanManager().hasVkContext() && mGrContext) {
271 return;
272 }
273 mVkManager->initialize();
274 GrContextOptions options;
275 initGrContextOptions(options);
276 auto vkDriverVersion = mVkManager->getDriverVersion();
277 cacheManager().configureContext(&options, &vkDriverVersion, sizeof(vkDriverVersion));
278 sk_sp<GrDirectContext> grContext = mVkManager->createContext(options);
279 LOG_ALWAYS_FATAL_IF(!grContext.get());
280 setGrContext(grContext);
281 }
282
initGrContextOptions(GrContextOptions & options)283 void RenderThread::initGrContextOptions(GrContextOptions& options) {
284 options.fPreferExternalImagesOverES3 = true;
285 options.fDisableDistanceFieldPaths = true;
286 if (android::base::GetBoolProperty(PROPERTY_REDUCE_OPS_TASK_SPLITTING, true)) {
287 options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kYes;
288 } else {
289 options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo;
290 }
291 }
292
destroyRenderingContext()293 void RenderThread::destroyRenderingContext() {
294 mFunctorManager.onContextDestroyed();
295 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
296 if (mEglManager->hasEglContext()) {
297 setGrContext(nullptr);
298 mEglManager->destroy();
299 }
300 } else {
301 setGrContext(nullptr);
302 mVkManager.clear();
303 }
304 }
305
vulkanManager()306 VulkanManager& RenderThread::vulkanManager() {
307 if (!mVkManager.get()) {
308 mVkManager = VulkanManager::getInstance();
309 }
310 return *mVkManager.get();
311 }
312
pipelineToString()313 static const char* pipelineToString() {
314 switch (auto renderType = Properties::getRenderPipelineType()) {
315 case RenderPipelineType::SkiaGL:
316 return "Skia (OpenGL)";
317 case RenderPipelineType::SkiaVulkan:
318 return "Skia (Vulkan)";
319 default:
320 LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t)renderType);
321 }
322 }
323
dumpGraphicsMemory(int fd,bool includeProfileData)324 void RenderThread::dumpGraphicsMemory(int fd, bool includeProfileData) {
325 if (includeProfileData) {
326 globalProfileData()->dump(fd);
327 }
328
329 String8 cachesOutput;
330 mCacheManager->dumpMemoryUsage(cachesOutput, mRenderState);
331 dprintf(fd, "\nPipeline=%s\n%s\n", pipelineToString(), cachesOutput.string());
332 }
333
getMemoryUsage(size_t * cpuUsage,size_t * gpuUsage)334 void RenderThread::getMemoryUsage(size_t* cpuUsage, size_t* gpuUsage) {
335 mCacheManager->getMemoryUsage(cpuUsage, gpuUsage);
336 }
337
readback()338 Readback& RenderThread::readback() {
339 if (!mReadback) {
340 mReadback = new Readback(*this);
341 }
342
343 return *mReadback;
344 }
345
setGrContext(sk_sp<GrDirectContext> context)346 void RenderThread::setGrContext(sk_sp<GrDirectContext> context) {
347 mCacheManager->reset(context);
348 if (mGrContext) {
349 mRenderState->onContextDestroyed();
350 mGrContext->releaseResourcesAndAbandonContext();
351 }
352 mGrContext = std::move(context);
353 if (mGrContext) {
354 DeviceInfo::setMaxTextureSize(mGrContext->maxRenderTargetSize());
355 }
356 }
357
requireGrContext()358 sk_sp<GrDirectContext> RenderThread::requireGrContext() {
359 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
360 requireGlContext();
361 } else {
362 requireVkContext();
363 }
364 return mGrContext;
365 }
366
choreographerCallback(int fd,int events,void * data)367 int RenderThread::choreographerCallback(int fd, int events, void* data) {
368 if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
369 ALOGE("Display event receiver pipe was closed or an error occurred. "
370 "events=0x%x",
371 events);
372 return 0; // remove the callback
373 }
374
375 if (!(events & Looper::EVENT_INPUT)) {
376 ALOGW("Received spurious callback for unhandled poll event. "
377 "events=0x%x",
378 events);
379 return 1; // keep the callback
380 }
381 RenderThread* rt = reinterpret_cast<RenderThread*>(data);
382 AChoreographer_handlePendingEvents(rt->mChoreographer, data);
383
384 return 1;
385 }
386
dispatchFrameCallbacks()387 void RenderThread::dispatchFrameCallbacks() {
388 ATRACE_CALL();
389 mFrameCallbackTaskPending = false;
390
391 std::set<IFrameCallback*> callbacks;
392 mFrameCallbacks.swap(callbacks);
393
394 if (callbacks.size()) {
395 // Assume one of them will probably animate again so preemptively
396 // request the next vsync in case it occurs mid-frame
397 requestVsync();
398 for (std::set<IFrameCallback*>::iterator it = callbacks.begin(); it != callbacks.end();
399 it++) {
400 (*it)->doFrame();
401 }
402 }
403 }
404
requestVsync()405 void RenderThread::requestVsync() {
406 if (!mVsyncRequested) {
407 mVsyncRequested = true;
408 mVsyncSource->requestNextVsync();
409 }
410 }
411
threadLoop()412 bool RenderThread::threadLoop() {
413 setpriority(PRIO_PROCESS, 0, PRIORITY_DISPLAY);
414 Looper::setForThread(mLooper);
415 if (gOnStartHook) {
416 gOnStartHook("RenderThread");
417 }
418 initThreadLocals();
419
420 while (true) {
421 waitForWork();
422 processQueue();
423
424 if (mPendingRegistrationFrameCallbacks.size() && !mFrameCallbackTaskPending) {
425 mVsyncSource->drainPendingEvents();
426 mFrameCallbacks.insert(mPendingRegistrationFrameCallbacks.begin(),
427 mPendingRegistrationFrameCallbacks.end());
428 mPendingRegistrationFrameCallbacks.clear();
429 requestVsync();
430 }
431
432 if (!mFrameCallbackTaskPending && !mVsyncRequested && mFrameCallbacks.size()) {
433 // TODO: Clean this up. This is working around an issue where a combination
434 // of bad timing and slow drawing can result in dropping a stale vsync
435 // on the floor (correct!) but fails to schedule to listen for the
436 // next vsync (oops), so none of the callbacks are run.
437 requestVsync();
438 }
439 }
440
441 return false;
442 }
443
postFrameCallback(IFrameCallback * callback)444 void RenderThread::postFrameCallback(IFrameCallback* callback) {
445 mPendingRegistrationFrameCallbacks.insert(callback);
446 }
447
removeFrameCallback(IFrameCallback * callback)448 bool RenderThread::removeFrameCallback(IFrameCallback* callback) {
449 size_t erased;
450 erased = mFrameCallbacks.erase(callback);
451 erased |= mPendingRegistrationFrameCallbacks.erase(callback);
452 return erased;
453 }
454
pushBackFrameCallback(IFrameCallback * callback)455 void RenderThread::pushBackFrameCallback(IFrameCallback* callback) {
456 if (mFrameCallbacks.erase(callback)) {
457 mPendingRegistrationFrameCallbacks.insert(callback);
458 }
459 }
460
allocateHardwareBitmap(SkBitmap & skBitmap)461 sk_sp<Bitmap> RenderThread::allocateHardwareBitmap(SkBitmap& skBitmap) {
462 auto renderType = Properties::getRenderPipelineType();
463 switch (renderType) {
464 case RenderPipelineType::SkiaVulkan:
465 return skiapipeline::SkiaVulkanPipeline::allocateHardwareBitmap(*this, skBitmap);
466 default:
467 LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t)renderType);
468 break;
469 }
470 return nullptr;
471 }
472
isCurrent()473 bool RenderThread::isCurrent() {
474 return gettid() == getInstance().getTid();
475 }
476
preload()477 void RenderThread::preload() {
478 // EGL driver is always preloaded only if HWUI renders with GL.
479 if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
480 std::thread eglInitThread([]() { eglGetDisplay(EGL_DEFAULT_DISPLAY); });
481 eglInitThread.detach();
482 } else {
483 requireVkContext();
484 }
485 HardwareBitmapUploader::initialize();
486 }
487
488 } /* namespace renderthread */
489 } /* namespace uirenderer */
490 } /* namespace android */
491