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 "../HardwareBitmapUploader.h"
20 #include "CanvasContext.h"
21 #include "DeviceInfo.h"
22 #include "EglManager.h"
23 #include "Readback.h"
24 #include "RenderProxy.h"
25 #include "VulkanManager.h"
26 #include "hwui/Bitmap.h"
27 #include "pipeline/skia/SkiaOpenGLPipeline.h"
28 #include "pipeline/skia/SkiaVulkanPipeline.h"
29 #include "renderstate/RenderState.h"
30 #include "utils/FatVector.h"
31 #include "utils/TimeUtils.h"
32 #include "utils/TraceUtils.h"
33 
34 #ifdef HWUI_GLES_WRAP_ENABLED
35 #include "debug/GlesDriver.h"
36 #endif
37 
38 #include <GrContextOptions.h>
39 #include <gl/GrGLInterface.h>
40 
41 #include <gui/DisplayEventReceiver.h>
42 #include <sys/resource.h>
43 #include <utils/Condition.h>
44 #include <utils/Log.h>
45 #include <utils/Mutex.h>
46 #include <thread>
47 
48 namespace android {
49 namespace uirenderer {
50 namespace renderthread {
51 
52 // Number of events to read at a time from the DisplayEventReceiver pipe.
53 // The value should be large enough that we can quickly drain the pipe
54 // using just a few large reads.
55 static const size_t EVENT_BUFFER_SIZE = 100;
56 
57 static bool gHasRenderThreadInstance = false;
58 
59 static JVMAttachHook gOnStartHook = nullptr;
60 
61 class DisplayEventReceiverWrapper : public VsyncSource {
62 public:
DisplayEventReceiverWrapper(std::unique_ptr<DisplayEventReceiver> && receiver,const std::function<void ()> & onDisplayConfigChanged)63     DisplayEventReceiverWrapper(std::unique_ptr<DisplayEventReceiver>&& receiver,
64             const std::function<void()>& onDisplayConfigChanged)
65             : mDisplayEventReceiver(std::move(receiver))
66             , mOnDisplayConfigChanged(onDisplayConfigChanged) {}
67 
requestNextVsync()68     virtual void requestNextVsync() override {
69         status_t status = mDisplayEventReceiver->requestNextVsync();
70         LOG_ALWAYS_FATAL_IF(status != NO_ERROR, "requestNextVsync failed with status: %d", status);
71     }
72 
latestVsyncEvent()73     virtual nsecs_t latestVsyncEvent() override {
74         DisplayEventReceiver::Event buf[EVENT_BUFFER_SIZE];
75         nsecs_t latest = 0;
76         ssize_t n;
77         while ((n = mDisplayEventReceiver->getEvents(buf, EVENT_BUFFER_SIZE)) > 0) {
78             for (ssize_t i = 0; i < n; i++) {
79                 const DisplayEventReceiver::Event& ev = buf[i];
80                 switch (ev.header.type) {
81                     case DisplayEventReceiver::DISPLAY_EVENT_VSYNC:
82                         latest = ev.header.timestamp;
83                         break;
84                     case DisplayEventReceiver::DISPLAY_EVENT_CONFIG_CHANGED:
85                         mOnDisplayConfigChanged();
86                         break;
87                 }
88             }
89         }
90         if (n < 0) {
91             ALOGW("Failed to get events from display event receiver, status=%d", status_t(n));
92         }
93         return latest;
94     }
95 
96 private:
97     std::unique_ptr<DisplayEventReceiver> mDisplayEventReceiver;
98     std::function<void()> mOnDisplayConfigChanged;
99 };
100 
101 class DummyVsyncSource : public VsyncSource {
102 public:
DummyVsyncSource(RenderThread * renderThread)103     DummyVsyncSource(RenderThread* renderThread) : mRenderThread(renderThread) {}
104 
requestNextVsync()105     virtual void requestNextVsync() override {
106         mRenderThread->queue().postDelayed(16_ms,
107                                            [this]() { mRenderThread->drainDisplayEventQueue(); });
108     }
109 
latestVsyncEvent()110     virtual nsecs_t latestVsyncEvent() override { return systemTime(CLOCK_MONOTONIC); }
111 
112 private:
113     RenderThread* mRenderThread;
114 };
115 
hasInstance()116 bool RenderThread::hasInstance() {
117     return gHasRenderThreadInstance;
118 }
119 
setOnStartHook(JVMAttachHook onStartHook)120 void RenderThread::setOnStartHook(JVMAttachHook onStartHook) {
121     LOG_ALWAYS_FATAL_IF(hasInstance(), "can't set an onStartHook after we've started...");
122     gOnStartHook = onStartHook;
123 }
124 
getOnStartHook()125 JVMAttachHook RenderThread::getOnStartHook() {
126     return gOnStartHook;
127 }
128 
getInstance()129 RenderThread& RenderThread::getInstance() {
130     // This is a pointer because otherwise __cxa_finalize
131     // will try to delete it like a Good Citizen but that causes us to crash
132     // because we don't want to delete the RenderThread normally.
133     static RenderThread* sInstance = new RenderThread();
134     gHasRenderThreadInstance = true;
135     return *sInstance;
136 }
137 
RenderThread()138 RenderThread::RenderThread()
139         : ThreadBase()
140         , mVsyncSource(nullptr)
141         , mVsyncRequested(false)
142         , mFrameCallbackTaskPending(false)
143         , mRenderState(nullptr)
144         , mEglManager(nullptr)
145         , mFunctorManager(WebViewFunctorManager::instance())
146         , mVkManager(nullptr) {
147     Properties::load();
148     start("RenderThread");
149 }
150 
~RenderThread()151 RenderThread::~RenderThread() {
152     LOG_ALWAYS_FATAL("Can't destroy the render thread");
153 }
154 
initializeDisplayEventReceiver()155 void RenderThread::initializeDisplayEventReceiver() {
156     LOG_ALWAYS_FATAL_IF(mVsyncSource, "Initializing a second DisplayEventReceiver?");
157 
158     if (!Properties::isolatedProcess) {
159         auto receiver = std::make_unique<DisplayEventReceiver>(
160             ISurfaceComposer::eVsyncSourceApp,
161             ISurfaceComposer::eConfigChangedDispatch);
162         status_t status = receiver->initCheck();
163         LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
164                             "Initialization of DisplayEventReceiver "
165                             "failed with status: %d",
166                             status);
167 
168         // Register the FD
169         mLooper->addFd(receiver->getFd(), 0, Looper::EVENT_INPUT,
170                        RenderThread::displayEventReceiverCallback, this);
171         mVsyncSource = new DisplayEventReceiverWrapper(std::move(receiver), [this] {
172             DeviceInfo::get()->onDisplayConfigChanged();
173             setupFrameInterval();
174         });
175     } else {
176         mVsyncSource = new DummyVsyncSource(this);
177     }
178 }
179 
initThreadLocals()180 void RenderThread::initThreadLocals() {
181     setupFrameInterval();
182     initializeDisplayEventReceiver();
183     mEglManager = new EglManager();
184     mRenderState = new RenderState(*this);
185     mVkManager = new VulkanManager();
186     mCacheManager = new CacheManager(DeviceInfo::get()->displayInfo());
187 }
188 
setupFrameInterval()189 void RenderThread::setupFrameInterval() {
190     auto& displayInfo = DeviceInfo::get()->displayInfo();
191     nsecs_t frameIntervalNanos = static_cast<nsecs_t>(1000000000 / displayInfo.fps);
192     mTimeLord.setFrameInterval(frameIntervalNanos);
193     mDispatchFrameDelay = static_cast<nsecs_t>(frameIntervalNanos * .25f);
194 }
195 
requireGlContext()196 void RenderThread::requireGlContext() {
197     if (mEglManager->hasEglContext()) {
198         return;
199     }
200     mEglManager->initialize();
201 
202 #ifdef HWUI_GLES_WRAP_ENABLED
203     debug::GlesDriver* driver = debug::GlesDriver::get();
204     sk_sp<const GrGLInterface> glInterface(driver->getSkiaInterface());
205 #else
206     sk_sp<const GrGLInterface> glInterface(GrGLCreateNativeInterface());
207 #endif
208     LOG_ALWAYS_FATAL_IF(!glInterface.get());
209 
210     GrContextOptions options;
211     initGrContextOptions(options);
212     auto glesVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
213     auto size = glesVersion ? strlen(glesVersion) : -1;
214     cacheManager().configureContext(&options, glesVersion, size);
215     sk_sp<GrContext> grContext(GrContext::MakeGL(std::move(glInterface), options));
216     LOG_ALWAYS_FATAL_IF(!grContext.get());
217     setGrContext(grContext);
218 }
219 
requireVkContext()220 void RenderThread::requireVkContext() {
221     if (mVkManager->hasVkContext()) {
222         return;
223     }
224     mVkManager->initialize();
225     GrContextOptions options;
226     initGrContextOptions(options);
227     auto vkDriverVersion = mVkManager->getDriverVersion();
228     cacheManager().configureContext(&options, &vkDriverVersion, sizeof(vkDriverVersion));
229     sk_sp<GrContext> grContext = mVkManager->createContext(options);
230     LOG_ALWAYS_FATAL_IF(!grContext.get());
231     setGrContext(grContext);
232 }
233 
initGrContextOptions(GrContextOptions & options)234 void RenderThread::initGrContextOptions(GrContextOptions& options) {
235     options.fPreferExternalImagesOverES3 = true;
236     options.fDisableDistanceFieldPaths = true;
237 }
238 
destroyRenderingContext()239 void RenderThread::destroyRenderingContext() {
240     mFunctorManager.onContextDestroyed();
241     if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
242         if (mEglManager->hasEglContext()) {
243             setGrContext(nullptr);
244             mEglManager->destroy();
245         }
246     } else {
247         if (vulkanManager().hasVkContext()) {
248             setGrContext(nullptr);
249             vulkanManager().destroy();
250         }
251     }
252 }
253 
dumpGraphicsMemory(int fd)254 void RenderThread::dumpGraphicsMemory(int fd) {
255     globalProfileData()->dump(fd);
256 
257     String8 cachesOutput;
258     String8 pipeline;
259     auto renderType = Properties::getRenderPipelineType();
260     switch (renderType) {
261         case RenderPipelineType::SkiaGL: {
262             mCacheManager->dumpMemoryUsage(cachesOutput, mRenderState);
263             pipeline.appendFormat("Skia (OpenGL)");
264             break;
265         }
266         case RenderPipelineType::SkiaVulkan: {
267             mCacheManager->dumpMemoryUsage(cachesOutput, mRenderState);
268             pipeline.appendFormat("Skia (Vulkan)");
269             break;
270         }
271         default:
272             LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t)renderType);
273             break;
274     }
275 
276     dprintf(fd, "\n%s\n", cachesOutput.string());
277     dprintf(fd, "\nPipeline=%s\n", pipeline.string());
278 }
279 
readback()280 Readback& RenderThread::readback() {
281     if (!mReadback) {
282         mReadback = new Readback(*this);
283     }
284 
285     return *mReadback;
286 }
287 
setGrContext(sk_sp<GrContext> context)288 void RenderThread::setGrContext(sk_sp<GrContext> context) {
289     mCacheManager->reset(context);
290     if (mGrContext) {
291         mRenderState->onContextDestroyed();
292         mGrContext->releaseResourcesAndAbandonContext();
293     }
294     mGrContext = std::move(context);
295     if (mGrContext) {
296         mRenderState->onContextCreated();
297         DeviceInfo::setMaxTextureSize(mGrContext->maxRenderTargetSize());
298     }
299 }
300 
displayEventReceiverCallback(int fd,int events,void * data)301 int RenderThread::displayEventReceiverCallback(int fd, int events, void* data) {
302     if (events & (Looper::EVENT_ERROR | Looper::EVENT_HANGUP)) {
303         ALOGE("Display event receiver pipe was closed or an error occurred.  "
304               "events=0x%x",
305               events);
306         return 0;  // remove the callback
307     }
308 
309     if (!(events & Looper::EVENT_INPUT)) {
310         ALOGW("Received spurious callback for unhandled poll event.  "
311               "events=0x%x",
312               events);
313         return 1;  // keep the callback
314     }
315 
316     reinterpret_cast<RenderThread*>(data)->drainDisplayEventQueue();
317 
318     return 1;  // keep the callback
319 }
320 
drainDisplayEventQueue()321 void RenderThread::drainDisplayEventQueue() {
322     ATRACE_CALL();
323     nsecs_t vsyncEvent = mVsyncSource->latestVsyncEvent();
324     if (vsyncEvent > 0) {
325         mVsyncRequested = false;
326         if (mTimeLord.vsyncReceived(vsyncEvent) && !mFrameCallbackTaskPending) {
327             ATRACE_NAME("queue mFrameCallbackTask");
328             mFrameCallbackTaskPending = true;
329             nsecs_t runAt = (vsyncEvent + mDispatchFrameDelay);
330             queue().postAt(runAt, [this]() { dispatchFrameCallbacks(); });
331         }
332     }
333 }
334 
dispatchFrameCallbacks()335 void RenderThread::dispatchFrameCallbacks() {
336     ATRACE_CALL();
337     mFrameCallbackTaskPending = false;
338 
339     std::set<IFrameCallback*> callbacks;
340     mFrameCallbacks.swap(callbacks);
341 
342     if (callbacks.size()) {
343         // Assume one of them will probably animate again so preemptively
344         // request the next vsync in case it occurs mid-frame
345         requestVsync();
346         for (std::set<IFrameCallback*>::iterator it = callbacks.begin(); it != callbacks.end();
347              it++) {
348             (*it)->doFrame();
349         }
350     }
351 }
352 
requestVsync()353 void RenderThread::requestVsync() {
354     if (!mVsyncRequested) {
355         mVsyncRequested = true;
356         mVsyncSource->requestNextVsync();
357     }
358 }
359 
threadLoop()360 bool RenderThread::threadLoop() {
361     setpriority(PRIO_PROCESS, 0, PRIORITY_DISPLAY);
362     Looper::setForThread(mLooper);
363     if (gOnStartHook) {
364         gOnStartHook("RenderThread");
365     }
366     initThreadLocals();
367 
368     while (true) {
369         waitForWork();
370         processQueue();
371 
372         if (mPendingRegistrationFrameCallbacks.size() && !mFrameCallbackTaskPending) {
373             drainDisplayEventQueue();
374             mFrameCallbacks.insert(mPendingRegistrationFrameCallbacks.begin(),
375                                    mPendingRegistrationFrameCallbacks.end());
376             mPendingRegistrationFrameCallbacks.clear();
377             requestVsync();
378         }
379 
380         if (!mFrameCallbackTaskPending && !mVsyncRequested && mFrameCallbacks.size()) {
381             // TODO: Clean this up. This is working around an issue where a combination
382             // of bad timing and slow drawing can result in dropping a stale vsync
383             // on the floor (correct!) but fails to schedule to listen for the
384             // next vsync (oops), so none of the callbacks are run.
385             requestVsync();
386         }
387     }
388 
389     return false;
390 }
391 
postFrameCallback(IFrameCallback * callback)392 void RenderThread::postFrameCallback(IFrameCallback* callback) {
393     mPendingRegistrationFrameCallbacks.insert(callback);
394 }
395 
removeFrameCallback(IFrameCallback * callback)396 bool RenderThread::removeFrameCallback(IFrameCallback* callback) {
397     size_t erased;
398     erased = mFrameCallbacks.erase(callback);
399     erased |= mPendingRegistrationFrameCallbacks.erase(callback);
400     return erased;
401 }
402 
pushBackFrameCallback(IFrameCallback * callback)403 void RenderThread::pushBackFrameCallback(IFrameCallback* callback) {
404     if (mFrameCallbacks.erase(callback)) {
405         mPendingRegistrationFrameCallbacks.insert(callback);
406     }
407 }
408 
allocateHardwareBitmap(SkBitmap & skBitmap)409 sk_sp<Bitmap> RenderThread::allocateHardwareBitmap(SkBitmap& skBitmap) {
410     auto renderType = Properties::getRenderPipelineType();
411     switch (renderType) {
412         case RenderPipelineType::SkiaVulkan:
413             return skiapipeline::SkiaVulkanPipeline::allocateHardwareBitmap(*this, skBitmap);
414         default:
415             LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t)renderType);
416             break;
417     }
418     return nullptr;
419 }
420 
isCurrent()421 bool RenderThread::isCurrent() {
422     return gettid() == getInstance().getTid();
423 }
424 
preload()425 void RenderThread::preload() {
426     // EGL driver is always preloaded only if HWUI renders with GL.
427     if (Properties::getRenderPipelineType() == RenderPipelineType::SkiaGL) {
428         std::thread eglInitThread([]() { eglGetDisplay(EGL_DEFAULT_DISPLAY); });
429         eglInitThread.detach();
430     } else {
431         requireVkContext();
432     }
433     HardwareBitmapUploader::initialize();
434 }
435 
436 } /* namespace renderthread */
437 } /* namespace uirenderer */
438 } /* namespace android */
439