Switch to a fancy new queue
Test: unit tests & benchmarks pass/faster
Change-Id: I9521432172d6dd6039c5280b1265479a36a86247
diff --git a/libs/hwui/Android.bp b/libs/hwui/Android.bp
index 40aecac..2644292 100644
--- a/libs/hwui/Android.bp
+++ b/libs/hwui/Android.bp
@@ -7,6 +7,8 @@
//"hwui_compile_for_perf",
],
+ cpp_std: "c++17",
+
cflags: [
"-DEGL_EGLEXT_PROTOTYPES",
"-DGL_GLEXT_PROTOTYPES",
@@ -354,7 +356,8 @@
"tests/unit/TestUtilsTests.cpp",
"tests/unit/TextDropShadowCacheTests.cpp",
"tests/unit/TextureCacheTests.cpp",
- "tests/unit/TypefaceTests.cpp",
+ "tests/unit/ThreadBaseTests.cpp",
+ "tests/unit/TypefaceTests.cpp",
"tests/unit/VectorDrawableTests.cpp",
"tests/unit/VectorDrawableAtlasTests.cpp",
],
diff --git a/libs/hwui/SwapBehavior.h b/libs/hwui/SwapBehavior.h
new file mode 100644
index 0000000..4091670c
--- /dev/null
+++ b/libs/hwui/SwapBehavior.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HWUI_SWAPBEHAVIOR_H
+#define HWUI_SWAPBEHAVIOR_H
+
+namespace android {
+namespace uirenderer {
+namespace renderthread {
+
+enum class SwapBehavior {
+ kSwap_default,
+ kSwap_discardBuffer,
+};
+
+} // namespace renderthread
+} //namespace uirenderer
+} // namespace android
+
+#endif //HWUI_SWAPBEHAVIOR_H
diff --git a/libs/hwui/renderstate/RenderState.cpp b/libs/hwui/renderstate/RenderState.cpp
index 6c606f7..0ceca33 100644
--- a/libs/hwui/renderstate/RenderState.cpp
+++ b/libs/hwui/renderstate/RenderState.cpp
@@ -236,25 +236,11 @@
std::for_each(mActiveLayerUpdaters.begin(), mActiveLayerUpdaters.end(), destroyLayerInUpdater);
}
-class DecStrongTask : public renderthread::RenderTask {
-public:
- explicit DecStrongTask(VirtualLightRefBase* object) : mObject(object) {}
-
- virtual void run() override {
- mObject->decStrong(nullptr);
- mObject = nullptr;
- delete this;
- }
-
-private:
- VirtualLightRefBase* mObject;
-};
-
void RenderState::postDecStrong(VirtualLightRefBase* object) {
if (pthread_equal(mThreadId, pthread_self())) {
object->decStrong(nullptr);
} else {
- mRenderThread.queue(new DecStrongTask(object));
+ mRenderThread.queue().post([object]() { object->decStrong(nullptr); });
}
}
diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp
index ad684db..36a0da1 100644
--- a/libs/hwui/renderthread/CanvasContext.cpp
+++ b/libs/hwui/renderthread/CanvasContext.cpp
@@ -181,13 +181,13 @@
mAnimationContext->destroy();
}
-void CanvasContext::setSurface(Surface* surface) {
+void CanvasContext::setSurface(sp<Surface>&& surface) {
ATRACE_CALL();
- mNativeSurface = surface;
+ mNativeSurface = std::move(surface);
ColorMode colorMode = mWideColorGamut ? ColorMode::WideColorGamut : ColorMode::Srgb;
- bool hasSurface = mRenderPipeline->setSurface(surface, mSwapBehavior, colorMode);
+ bool hasSurface = mRenderPipeline->setSurface(mNativeSurface.get(), mSwapBehavior, colorMode);
mFrameNumber = -1;
@@ -203,15 +203,7 @@
mSwapBehavior = swapBehavior;
}
-void CanvasContext::initialize(Surface* surface) {
- setSurface(surface);
-}
-
-void CanvasContext::updateSurface(Surface* surface) {
- setSurface(surface);
-}
-
-bool CanvasContext::pauseSurface(Surface* surface) {
+bool CanvasContext::pauseSurface() {
return mRenderThread.removeFrameCallback(this);
}
diff --git a/libs/hwui/renderthread/CanvasContext.h b/libs/hwui/renderthread/CanvasContext.h
index 4a5b2c7..f8a8775 100644
--- a/libs/hwui/renderthread/CanvasContext.h
+++ b/libs/hwui/renderthread/CanvasContext.h
@@ -117,9 +117,8 @@
// Won't take effect until next EGLSurface creation
void setSwapBehavior(SwapBehavior swapBehavior);
- void initialize(Surface* surface);
- void updateSurface(Surface* surface);
- bool pauseSurface(Surface* surface);
+ void setSurface(sp<Surface>&& surface);
+ bool pauseSurface();
void setStopped(bool stopped);
bool hasSurface() { return mNativeSurface.get(); }
@@ -205,8 +204,6 @@
// lifecycle tracking
friend class android::uirenderer::RenderState;
- void setSurface(Surface* window);
-
void freePrefetchedLayers();
bool isSwapChainStuffed();
diff --git a/libs/hwui/renderthread/DrawFrameTask.cpp b/libs/hwui/renderthread/DrawFrameTask.cpp
index a097272..0a94678 100644
--- a/libs/hwui/renderthread/DrawFrameTask.cpp
+++ b/libs/hwui/renderthread/DrawFrameTask.cpp
@@ -78,7 +78,7 @@
void DrawFrameTask::postAndWait() {
AutoMutex _lock(mLock);
- mRenderThread->queue(this);
+ mRenderThread->queue().post([this]() { run(); });
mSignal.wait(mLock);
}
diff --git a/libs/hwui/renderthread/DrawFrameTask.h b/libs/hwui/renderthread/DrawFrameTask.h
index 83ecb98..4e4b6da 100644
--- a/libs/hwui/renderthread/DrawFrameTask.h
+++ b/libs/hwui/renderthread/DrawFrameTask.h
@@ -55,7 +55,7 @@
* tracked across many frames not just a single frame.
* It is the sync-state task, and will kick off the post-sync draw
*/
-class DrawFrameTask : public RenderTask {
+class DrawFrameTask {
public:
DrawFrameTask();
virtual ~DrawFrameTask();
@@ -72,7 +72,7 @@
int64_t* frameInfo() { return mFrameInfo; }
- virtual void run() override;
+ void run();
private:
void postAndWait();
diff --git a/libs/hwui/renderthread/IRenderPipeline.h b/libs/hwui/renderthread/IRenderPipeline.h
index 0bb3889..cfc71cb 100644
--- a/libs/hwui/renderthread/IRenderPipeline.h
+++ b/libs/hwui/renderthread/IRenderPipeline.h
@@ -17,6 +17,7 @@
#pragma once
#include "FrameInfoVisualizer.h"
+#include "SwapBehavior.h"
#include <SkRect.h>
#include <utils/RefBase.h>
@@ -33,11 +34,6 @@
namespace renderthread {
-enum class SwapBehavior {
- kSwap_default,
- kSwap_discardBuffer,
-};
-
enum class MakeCurrentResult {
AlreadyCurrent,
Failed,
diff --git a/libs/hwui/renderthread/RenderProxy.cpp b/libs/hwui/renderthread/RenderProxy.cpp
index a6aa301..2f406da 100644
--- a/libs/hwui/renderthread/RenderProxy.cpp
+++ b/libs/hwui/renderthread/RenderProxy.cpp
@@ -36,46 +36,12 @@
namespace uirenderer {
namespace renderthread {
-#define ARGS(method) method ## Args
-
-#define CREATE_BRIDGE0(name) CREATE_BRIDGE(name,,,,,,,,)
-#define CREATE_BRIDGE1(name, a1) CREATE_BRIDGE(name, a1,,,,,,,)
-#define CREATE_BRIDGE2(name, a1, a2) CREATE_BRIDGE(name, a1,a2,,,,,,)
-#define CREATE_BRIDGE3(name, a1, a2, a3) CREATE_BRIDGE(name, a1,a2,a3,,,,,)
-#define CREATE_BRIDGE4(name, a1, a2, a3, a4) CREATE_BRIDGE(name, a1,a2,a3,a4,,,,)
-#define CREATE_BRIDGE5(name, a1, a2, a3, a4, a5) CREATE_BRIDGE(name, a1,a2,a3,a4,a5,,,)
-#define CREATE_BRIDGE6(name, a1, a2, a3, a4, a5, a6) CREATE_BRIDGE(name, a1,a2,a3,a4,a5,a6,,)
-#define CREATE_BRIDGE7(name, a1, a2, a3, a4, a5, a6, a7) CREATE_BRIDGE(name, a1,a2,a3,a4,a5,a6,a7,)
-#define CREATE_BRIDGE(name, a1, a2, a3, a4, a5, a6, a7, a8) \
- typedef struct { \
- a1; a2; a3; a4; a5; a6; a7; a8; \
- } ARGS(name); \
- static_assert(std::is_trivially_destructible<ARGS(name)>::value, \
- "Error, ARGS must be trivially destructible!"); \
- static void* Bridge_ ## name(ARGS(name)* args)
-
-#define SETUP_TASK(method) \
- LOG_ALWAYS_FATAL_IF( METHOD_INVOKE_PAYLOAD_SIZE < sizeof(ARGS(method)), \
- "METHOD_INVOKE_PAYLOAD_SIZE %zu is smaller than sizeof(" #method "Args) %zu", \
- METHOD_INVOKE_PAYLOAD_SIZE, sizeof(ARGS(method))); \
- MethodInvokeRenderTask* task = new MethodInvokeRenderTask((RunnableMethod) Bridge_ ## method); \
- ARGS(method) *args = (ARGS(method) *) task->payload()
-
-CREATE_BRIDGE4(createContext, RenderThread* thread, bool translucent,
- RenderNode* rootRenderNode, IContextFactory* contextFactory) {
- return CanvasContext::create(*args->thread, args->translucent,
- args->rootRenderNode, args->contextFactory);
-}
-
RenderProxy::RenderProxy(bool translucent, RenderNode* rootRenderNode, IContextFactory* contextFactory)
: mRenderThread(RenderThread::getInstance())
, mContext(nullptr) {
- SETUP_TASK(createContext);
- args->translucent = translucent;
- args->rootRenderNode = rootRenderNode;
- args->thread = &mRenderThread;
- args->contextFactory = contextFactory;
- mContext = (CanvasContext*) postAndWait(task);
+ mContext = mRenderThread.queue().runSync([&]() -> CanvasContext* {
+ return CanvasContext::create(mRenderThread, translucent, rootRenderNode, contextFactory);
+ });
mDrawFrameTask.setContext(&mRenderThread, mContext, rootRenderNode);
}
@@ -83,162 +49,91 @@
destroyContext();
}
-CREATE_BRIDGE1(destroyContext, CanvasContext* context) {
- delete args->context;
- return nullptr;
-}
-
void RenderProxy::destroyContext() {
if (mContext) {
- SETUP_TASK(destroyContext);
- args->context = mContext;
- mContext = nullptr;
mDrawFrameTask.setContext(nullptr, nullptr, nullptr);
// This is also a fence as we need to be certain that there are no
// outstanding mDrawFrame tasks posted before it is destroyed
- postAndWait(task);
+ mRenderThread.queue().runSync([this]() {
+ delete mContext;
+ });
+ mContext = nullptr;
}
}
-CREATE_BRIDGE2(setSwapBehavior, CanvasContext* context, SwapBehavior swapBehavior) {
- args->context->setSwapBehavior(args->swapBehavior);
- return nullptr;
-}
-
void RenderProxy::setSwapBehavior(SwapBehavior swapBehavior) {
- SETUP_TASK(setSwapBehavior);
- args->context = mContext;
- args->swapBehavior = swapBehavior;
- post(task);
-}
-
-CREATE_BRIDGE1(loadSystemProperties, CanvasContext* context) {
- bool needsRedraw = false;
- if (Caches::hasInstance()) {
- needsRedraw = Properties::load();
- }
- if (args->context->profiler().consumeProperties()) {
- needsRedraw = true;
- }
- return (void*) needsRedraw;
+ mRenderThread.queue().post([this, swapBehavior]() {
+ mContext->setSwapBehavior(swapBehavior);
+ });
}
bool RenderProxy::loadSystemProperties() {
- SETUP_TASK(loadSystemProperties);
- args->context = mContext;
- return (bool) postAndWait(task);
-}
-
-CREATE_BRIDGE2(setName, CanvasContext* context, const char* name) {
- args->context->setName(std::string(args->name));
- return nullptr;
+ return mRenderThread.queue().runSync([this]() -> bool {
+ bool needsRedraw = false;
+ if (Caches::hasInstance()) {
+ needsRedraw = Properties::load();
+ }
+ if (mContext->profiler().consumeProperties()) {
+ needsRedraw = true;
+ }
+ return needsRedraw;
+ });
}
void RenderProxy::setName(const char* name) {
- SETUP_TASK(setName);
- args->context = mContext;
- args->name = name;
- postAndWait(task); // block since name/value pointers owned by caller
-}
-
-CREATE_BRIDGE2(initialize, CanvasContext* context, Surface* surface) {
- args->context->initialize(args->surface);
- return nullptr;
+ // block since name/value pointers owned by caller
+ // TODO: Support move arguments
+ mRenderThread.queue().runSync([this, name]() {
+ mContext->setName(std::string(name));
+ });
}
void RenderProxy::initialize(const sp<Surface>& surface) {
- SETUP_TASK(initialize);
- args->context = mContext;
- args->surface = surface.get();
- post(task);
-}
-
-CREATE_BRIDGE2(updateSurface, CanvasContext* context, Surface* surface) {
- args->context->updateSurface(args->surface);
- return nullptr;
+ mRenderThread.queue().post([this, surf = surface]() mutable {
+ mContext->setSurface(std::move(surf));
+ });
}
void RenderProxy::updateSurface(const sp<Surface>& surface) {
- SETUP_TASK(updateSurface);
- args->context = mContext;
- args->surface = surface.get();
- post(task);
-}
-
-CREATE_BRIDGE2(pauseSurface, CanvasContext* context, Surface* surface) {
- return (void*) args->context->pauseSurface(args->surface);
+ mRenderThread.queue().post([this, surf = surface]() mutable {
+ mContext->setSurface(std::move(surf));
+ });
}
bool RenderProxy::pauseSurface(const sp<Surface>& surface) {
- SETUP_TASK(pauseSurface);
- args->context = mContext;
- args->surface = surface.get();
- return (bool) postAndWait(task);
-}
-
-CREATE_BRIDGE2(setStopped, CanvasContext* context, bool stopped) {
- args->context->setStopped(args->stopped);
- return nullptr;
+ return mRenderThread.queue().runSync([this]() -> bool {
+ return mContext->pauseSurface();
+ });
}
void RenderProxy::setStopped(bool stopped) {
- SETUP_TASK(setStopped);
- args->context = mContext;
- args->stopped = stopped;
- postAndWait(task);
+ mRenderThread.queue().runSync([this, stopped]() {
+ mContext->setStopped(stopped);
+ });
}
-CREATE_BRIDGE4(setup, CanvasContext* context,
- float lightRadius, uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
- args->context->setup(args->lightRadius,
- args->ambientShadowAlpha, args->spotShadowAlpha);
- return nullptr;
-}
-
-void RenderProxy::setup(float lightRadius,
- uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
- SETUP_TASK(setup);
- args->context = mContext;
- args->lightRadius = lightRadius;
- args->ambientShadowAlpha = ambientShadowAlpha;
- args->spotShadowAlpha = spotShadowAlpha;
- post(task);
-}
-
-CREATE_BRIDGE2(setLightCenter, CanvasContext* context, Vector3 lightCenter) {
- args->context->setLightCenter(args->lightCenter);
- return nullptr;
+void RenderProxy::setup(float lightRadius, uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
+ mRenderThread.queue().post([=]() {
+ mContext->setup(lightRadius, ambientShadowAlpha, spotShadowAlpha);
+ });
}
void RenderProxy::setLightCenter(const Vector3& lightCenter) {
- SETUP_TASK(setLightCenter);
- args->context = mContext;
- args->lightCenter = lightCenter;
- post(task);
-}
-
-CREATE_BRIDGE2(setOpaque, CanvasContext* context, bool opaque) {
- args->context->setOpaque(args->opaque);
- return nullptr;
+ mRenderThread.queue().post([=]() {
+ mContext->setLightCenter(lightCenter);
+ });
}
void RenderProxy::setOpaque(bool opaque) {
- SETUP_TASK(setOpaque);
- args->context = mContext;
- args->opaque = opaque;
- post(task);
-}
-
-CREATE_BRIDGE2(setWideGamut, CanvasContext* context, bool wideGamut) {
- args->context->setWideGamut(args->wideGamut);
- return nullptr;
+ mRenderThread.queue().post([=]() {
+ mContext->setOpaque(opaque);
+ });
}
void RenderProxy::setWideGamut(bool wideGamut) {
- SETUP_TASK(setWideGamut);
- args->context = mContext;
- args->wideGamut = wideGamut;
- post(task);
+ mRenderThread.queue().post([=]() {
+ mContext->setWideGamut(wideGamut);
+ });
}
int64_t* RenderProxy::frameInfo() {
@@ -249,77 +144,45 @@
return mDrawFrameTask.drawFrame();
}
-CREATE_BRIDGE1(destroy, CanvasContext* context) {
- args->context->destroy();
- return nullptr;
-}
-
void RenderProxy::destroy() {
- SETUP_TASK(destroy);
- args->context = mContext;
// destroyCanvasAndSurface() needs a fence as when it returns the
// underlying BufferQueue is going to be released from under
// the render thread.
- postAndWait(task);
-}
-
-CREATE_BRIDGE2(invokeFunctor, RenderThread* thread, Functor* functor) {
- CanvasContext::invokeFunctor(*args->thread, args->functor);
- return nullptr;
+ mRenderThread.queue().runSync([=]() {
+ mContext->destroy();
+ });
}
void RenderProxy::invokeFunctor(Functor* functor, bool waitForCompletion) {
ATRACE_CALL();
RenderThread& thread = RenderThread::getInstance();
- SETUP_TASK(invokeFunctor);
- args->thread = &thread;
- args->functor = functor;
+ auto invoke = [&thread, functor]() { CanvasContext::invokeFunctor(thread, functor); };
if (waitForCompletion) {
// waitForCompletion = true is expected to be fairly rare and only
// happen in destruction. Thus it should be fine to temporarily
// create a Mutex
- staticPostAndWait(task);
+ thread.queue().runSync(std::move(invoke));
} else {
- thread.queue(task);
+ thread.queue().post(std::move(invoke));
}
}
-CREATE_BRIDGE1(createTextureLayer, CanvasContext* context) {
- return args->context->createTextureLayer();
-}
-
DeferredLayerUpdater* RenderProxy::createTextureLayer() {
- SETUP_TASK(createTextureLayer);
- args->context = mContext;
- void* retval = postAndWait(task);
- DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(retval);
- return layer;
-}
-
-CREATE_BRIDGE2(buildLayer, CanvasContext* context, RenderNode* node) {
- args->context->buildLayer(args->node);
- return nullptr;
+ return mRenderThread.queue().runSync([this]() -> auto {
+ return mContext->createTextureLayer();
+ });
}
void RenderProxy::buildLayer(RenderNode* node) {
- SETUP_TASK(buildLayer);
- args->context = mContext;
- args->node = node;
- postAndWait(task);
-}
-
-CREATE_BRIDGE3(copyLayerInto, CanvasContext* context, DeferredLayerUpdater* layer,
- SkBitmap* bitmap) {
- bool success = args->context->copyLayerInto(args->layer, args->bitmap);
- return (void*) success;
+ mRenderThread.queue().runSync([&]() {
+ mContext->buildLayer(node);
+ });
}
bool RenderProxy::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap& bitmap) {
- SETUP_TASK(copyLayerInto);
- args->context = mContext;
- args->layer = layer;
- args->bitmap = &bitmap;
- return (bool) postAndWait(task);
+ return mRenderThread.queue().runSync([&]() -> bool {
+ return mContext->copyLayerInto(layer, &bitmap);
+ });
}
void RenderProxy::pushLayerUpdate(DeferredLayerUpdater* layer) {
@@ -330,302 +193,154 @@
mDrawFrameTask.removeLayerUpdate(layer);
}
-CREATE_BRIDGE1(detachSurfaceTexture, DeferredLayerUpdater* layer) {
- args->layer->detachSurfaceTexture();
- return nullptr;
-}
-
void RenderProxy::detachSurfaceTexture(DeferredLayerUpdater* layer) {
- SETUP_TASK(detachSurfaceTexture);
- args->layer = layer;
- postAndWait(task);
-}
-
-CREATE_BRIDGE1(destroyHardwareResources, CanvasContext* context) {
- args->context->destroyHardwareResources();
- return nullptr;
+ return mRenderThread.queue().runSync([&]() {
+ layer->detachSurfaceTexture();
+ });
}
void RenderProxy::destroyHardwareResources() {
- SETUP_TASK(destroyHardwareResources);
- args->context = mContext;
- postAndWait(task);
-}
-
-CREATE_BRIDGE2(trimMemory, RenderThread* thread, int level) {
- CanvasContext::trimMemory(*args->thread, args->level);
- return nullptr;
+ return mRenderThread.queue().runSync([&]() {
+ mContext->destroyHardwareResources();
+ });
}
void RenderProxy::trimMemory(int level) {
// Avoid creating a RenderThread to do a trimMemory.
if (RenderThread::hasInstance()) {
RenderThread& thread = RenderThread::getInstance();
- SETUP_TASK(trimMemory);
- args->thread = &thread;
- args->level = level;
- thread.queue(task);
+ thread.queue().post([&thread, level]() {
+ CanvasContext::trimMemory(thread, level);
+ });
}
}
-CREATE_BRIDGE2(overrideProperty, const char* name, const char* value) {
- Properties::overrideProperty(args->name, args->value);
- return nullptr;
-}
-
void RenderProxy::overrideProperty(const char* name, const char* value) {
- SETUP_TASK(overrideProperty);
- args->name = name;
- args->value = value;
- staticPostAndWait(task); // expensive, but block here since name/value pointers owned by caller
+ // expensive, but block here since name/value pointers owned by caller
+ RenderThread::getInstance().queue().runSync([&]() {
+ Properties::overrideProperty(name, value);
+ });
}
-CREATE_BRIDGE0(fence) {
- // Intentionally empty
- return nullptr;
-}
-
-template <typename T>
-void UNUSED(T t) {}
-
void RenderProxy::fence() {
- SETUP_TASK(fence);
- UNUSED(args);
- postAndWait(task);
+ mRenderThread.queue().runSync([](){});
}
void RenderProxy::staticFence() {
- SETUP_TASK(fence);
- UNUSED(args);
- staticPostAndWait(task);
-}
-
-CREATE_BRIDGE1(stopDrawing, CanvasContext* context) {
- args->context->stopDrawing();
- return nullptr;
+ RenderThread::getInstance().queue().runSync([](){});
}
void RenderProxy::stopDrawing() {
- SETUP_TASK(stopDrawing);
- args->context = mContext;
- postAndWait(task);
-}
-
-CREATE_BRIDGE1(notifyFramePending, CanvasContext* context) {
- args->context->notifyFramePending();
- return nullptr;
+ mRenderThread.queue().runSync([this]() {
+ mContext->stopDrawing();
+ });
}
void RenderProxy::notifyFramePending() {
- SETUP_TASK(notifyFramePending);
- args->context = mContext;
- mRenderThread.queueAtFront(task);
-}
-
-CREATE_BRIDGE4(dumpProfileInfo, CanvasContext* context, RenderThread* thread,
- int fd, int dumpFlags) {
- args->context->profiler().dumpData(args->fd);
- if (args->dumpFlags & DumpFlags::FrameStats) {
- args->context->dumpFrames(args->fd);
- }
- if (args->dumpFlags & DumpFlags::JankStats) {
- args->thread->globalProfileData()->dump(args->fd);
- }
- if (args->dumpFlags & DumpFlags::Reset) {
- args->context->resetFrameStats();
- }
- return nullptr;
+ mRenderThread.queue().post([this]() {
+ mContext->notifyFramePending();
+ });
}
void RenderProxy::dumpProfileInfo(int fd, int dumpFlags) {
- SETUP_TASK(dumpProfileInfo);
- args->context = mContext;
- args->thread = &mRenderThread;
- args->fd = fd;
- args->dumpFlags = dumpFlags;
- postAndWait(task);
-}
-
-CREATE_BRIDGE1(resetProfileInfo, CanvasContext* context) {
- args->context->resetFrameStats();
- return nullptr;
+ mRenderThread.queue().runSync([&]() {
+ mContext->profiler().dumpData(fd);
+ if (dumpFlags & DumpFlags::FrameStats) {
+ mContext->dumpFrames(fd);
+ }
+ if (dumpFlags & DumpFlags::JankStats) {
+ mRenderThread.globalProfileData()->dump(fd);
+ }
+ if (dumpFlags & DumpFlags::Reset) {
+ mContext->resetFrameStats();
+ }
+ });
}
void RenderProxy::resetProfileInfo() {
- SETUP_TASK(resetProfileInfo);
- args->context = mContext;
- postAndWait(task);
+ mRenderThread.queue().runSync([=]() {
+ mContext->resetFrameStats();
+ });
}
-CREATE_BRIDGE2(frameTimePercentile, RenderThread* thread, int percentile) {
- return reinterpret_cast<void*>(static_cast<uintptr_t>(
- args->thread->globalProfileData()->findPercentile(args->percentile)));
-}
-
-uint32_t RenderProxy::frameTimePercentile(int p) {
- SETUP_TASK(frameTimePercentile);
- args->thread = &mRenderThread;
- args->percentile = p;
- return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(
- postAndWait(task)));
-}
-
-CREATE_BRIDGE2(dumpGraphicsMemory, int fd, RenderThread* thread) {
- args->thread->dumpGraphicsMemory(args->fd);
- return nullptr;
+uint32_t RenderProxy::frameTimePercentile(int percentile) {
+ return mRenderThread.queue().runSync([&]() -> auto {
+ return mRenderThread.globalProfileData()->findPercentile(percentile);
+ });
}
void RenderProxy::dumpGraphicsMemory(int fd) {
- if (!RenderThread::hasInstance()) return;
- SETUP_TASK(dumpGraphicsMemory);
- args->fd = fd;
- args->thread = &RenderThread::getInstance();
- staticPostAndWait(task);
-}
-
-CREATE_BRIDGE2(setProcessStatsBuffer, RenderThread* thread, int fd) {
- args->thread->globalProfileData().switchStorageToAshmem(args->fd);
- close(args->fd);
- return nullptr;
+ auto& thread = RenderThread::getInstance();
+ thread.queue().runSync([&]() {
+ thread.dumpGraphicsMemory(fd);
+ });
}
void RenderProxy::setProcessStatsBuffer(int fd) {
- SETUP_TASK(setProcessStatsBuffer);
auto& rt = RenderThread::getInstance();
- args->thread = &rt;
- args->fd = dup(fd);
- rt.queue(task);
-}
-
-CREATE_BRIDGE1(rotateProcessStatsBuffer, RenderThread* thread) {
- args->thread->globalProfileData().rotateStorage();
- return nullptr;
+ rt.queue().post([&rt, fd = dup(fd)]() {
+ rt.globalProfileData().switchStorageToAshmem(fd);
+ close(fd);
+ });
}
void RenderProxy::rotateProcessStatsBuffer() {
- SETUP_TASK(rotateProcessStatsBuffer);
auto& rt = RenderThread::getInstance();
- args->thread = &rt;
- rt.queue(task);
+ rt.queue().post([&rt]() {
+ rt.globalProfileData().rotateStorage();
+ });
}
int RenderProxy::getRenderThreadTid() {
return mRenderThread.getTid();
}
-CREATE_BRIDGE3(addRenderNode, CanvasContext* context, RenderNode* node, bool placeFront) {
- args->context->addRenderNode(args->node, args->placeFront);
- return nullptr;
-}
-
void RenderProxy::addRenderNode(RenderNode* node, bool placeFront) {
- SETUP_TASK(addRenderNode);
- args->context = mContext;
- args->node = node;
- args->placeFront = placeFront;
- post(task);
-}
-
-CREATE_BRIDGE2(removeRenderNode, CanvasContext* context, RenderNode* node) {
- args->context->removeRenderNode(args->node);
- return nullptr;
+ mRenderThread.queue().post([=]() {
+ mContext->addRenderNode(node, placeFront);
+ });
}
void RenderProxy::removeRenderNode(RenderNode* node) {
- SETUP_TASK(removeRenderNode);
- args->context = mContext;
- args->node = node;
- post(task);
-}
-
-CREATE_BRIDGE2(drawRenderNode, CanvasContext* context, RenderNode* node) {
- args->context->prepareAndDraw(args->node);
- return nullptr;
+ mRenderThread.queue().post([=]() {
+ mContext->removeRenderNode(node);
+ });
}
void RenderProxy::drawRenderNode(RenderNode* node) {
- SETUP_TASK(drawRenderNode);
- args->context = mContext;
- args->node = node;
- // Be pseudo-thread-safe and don't use any member variables
- staticPostAndWait(task);
+ mRenderThread.queue().runSync([=]() {
+ mContext->prepareAndDraw(node);
+ });
}
void RenderProxy::setContentDrawBounds(int left, int top, int right, int bottom) {
mDrawFrameTask.setContentDrawBounds(left, top, right, bottom);
}
-CREATE_BRIDGE1(serializeDisplayListTree, CanvasContext* context) {
- args->context->serializeDisplayListTree();
- return nullptr;
-}
-
void RenderProxy::serializeDisplayListTree() {
- SETUP_TASK(serializeDisplayListTree);
- args->context = mContext;
- post(task);
+ mRenderThread.queue().post([=]() {
+ mContext->serializeDisplayListTree();
+ });
}
-CREATE_BRIDGE2(addFrameMetricsObserver, CanvasContext* context,
- FrameMetricsObserver* frameStatsObserver) {
- args->context->addFrameMetricsObserver(args->frameStatsObserver);
- if (args->frameStatsObserver != nullptr) {
- args->frameStatsObserver->decStrong(args->context);
- }
- return nullptr;
+void RenderProxy::addFrameMetricsObserver(FrameMetricsObserver* observerPtr) {
+ mRenderThread.queue().post([this, observer = sp{observerPtr}]() {
+ mContext->addFrameMetricsObserver(observer.get());
+ });
}
-void RenderProxy::addFrameMetricsObserver(FrameMetricsObserver* observer) {
- SETUP_TASK(addFrameMetricsObserver);
- args->context = mContext;
- args->frameStatsObserver = observer;
- if (observer != nullptr) {
- observer->incStrong(mContext);
- }
- post(task);
-}
-
-CREATE_BRIDGE2(removeFrameMetricsObserver, CanvasContext* context,
- FrameMetricsObserver* frameStatsObserver) {
- args->context->removeFrameMetricsObserver(args->frameStatsObserver);
- if (args->frameStatsObserver != nullptr) {
- args->frameStatsObserver->decStrong(args->context);
- }
- return nullptr;
-}
-
-void RenderProxy::removeFrameMetricsObserver(FrameMetricsObserver* observer) {
- SETUP_TASK(removeFrameMetricsObserver);
- args->context = mContext;
- args->frameStatsObserver = observer;
- if (observer != nullptr) {
- observer->incStrong(mContext);
- }
- post(task);
-}
-
-CREATE_BRIDGE4(copySurfaceInto, RenderThread* thread,
- Surface* surface, Rect srcRect, SkBitmap* bitmap) {
- return (void*)args->thread->readback().copySurfaceInto(*args->surface,
- args->srcRect, args->bitmap);
+void RenderProxy::removeFrameMetricsObserver(FrameMetricsObserver* observerPtr) {
+ mRenderThread.queue().post([this, observer = sp{observerPtr}]() {
+ mContext->removeFrameMetricsObserver(observer.get());
+ });
}
int RenderProxy::copySurfaceInto(sp<Surface>& surface, int left, int top,
int right, int bottom, SkBitmap* bitmap) {
- SETUP_TASK(copySurfaceInto);
- args->bitmap = bitmap;
- args->surface = surface.get();
- args->thread = &RenderThread::getInstance();
- args->srcRect.set(left, top, right, bottom);
- return static_cast<int>(
- reinterpret_cast<intptr_t>( staticPostAndWait(task) ));
-}
-
-CREATE_BRIDGE2(prepareToDraw, RenderThread* thread, Bitmap* bitmap) {
- CanvasContext::prepareToDraw(*args->thread, args->bitmap);
- args->bitmap->unref();
- args->bitmap = nullptr;
- return nullptr;
+ auto& thread = RenderThread::getInstance();
+ return static_cast<int>(thread.queue().runSync([&]() -> auto {
+ return thread.readback().copySurfaceInto(*surface, Rect(left, top, right, bottom), bitmap);
+ }));
}
void RenderProxy::prepareToDraw(Bitmap& bitmap) {
@@ -635,10 +350,11 @@
// window or not.
if (!RenderThread::hasInstance()) return;
RenderThread* renderThread = &RenderThread::getInstance();
- SETUP_TASK(prepareToDraw);
- args->thread = renderThread;
bitmap.ref();
- args->bitmap = &bitmap;
+ auto task = [renderThread, &bitmap]() {
+ CanvasContext::prepareToDraw(*renderThread, &bitmap);
+ bitmap.unref();
+ };
nsecs_t lastVsync = renderThread->timeLord().latestVsync();
nsecs_t estimatedNextVsync = lastVsync + renderThread->timeLord().frameIntervalNanos();
nsecs_t timeToNextVsync = estimatedNextVsync - systemTime(CLOCK_MONOTONIC);
@@ -648,27 +364,17 @@
// TODO: Make this concept a first-class supported thing? RT could use
// knowledge of pending draws to better schedule this task
if (timeToNextVsync > -6_ms && timeToNextVsync < 1_ms) {
- renderThread->queueAt(task, estimatedNextVsync + 8_ms);
+ renderThread->queue().postAt(estimatedNextVsync + 8_ms, task);
} else {
- renderThread->queue(task);
+ renderThread->queue().post(task);
}
}
-CREATE_BRIDGE2(allocateHardwareBitmap, RenderThread* thread, SkBitmap* bitmap) {
- sk_sp<Bitmap> hardwareBitmap = args->thread->allocateHardwareBitmap(*args->bitmap);
- return hardwareBitmap.release();
-}
-
sk_sp<Bitmap> RenderProxy::allocateHardwareBitmap(SkBitmap& bitmap) {
- SETUP_TASK(allocateHardwareBitmap);
- args->bitmap = &bitmap;
- args->thread = &RenderThread::getInstance();
- sk_sp<Bitmap> hardwareBitmap(reinterpret_cast<Bitmap*>(staticPostAndWait(task)));
- return hardwareBitmap;
-}
-
-CREATE_BRIDGE3(copyGraphicBufferInto, RenderThread* thread, GraphicBuffer* buffer, SkBitmap* bitmap) {
- return (void*) args->thread->readback().copyGraphicBufferInto(args->buffer, args->bitmap);
+ auto& thread = RenderThread::getInstance();
+ return thread.queue().runSync([&]() -> auto {
+ return thread.allocateHardwareBitmap(bitmap);
+ });
}
int RenderProxy::copyGraphicBufferInto(GraphicBuffer* buffer, SkBitmap* bitmap) {
@@ -677,80 +383,36 @@
//TODO: fix everything that hits this. We should never be triggering a readback ourselves.
return (int) thread.readback().copyGraphicBufferInto(buffer, bitmap);
} else {
- SETUP_TASK(copyGraphicBufferInto);
- args->thread = &thread;
- args->bitmap = bitmap;
- args->buffer = buffer;
- return static_cast<int>(reinterpret_cast<intptr_t>(staticPostAndWait(task)));
+ return thread.queue().runSync([&]() -> int {
+ return (int) thread.readback().copyGraphicBufferInto(buffer, bitmap);
+ });
}
}
-CREATE_BRIDGE2(onBitmapDestroyed, RenderThread* thread, uint32_t pixelRefId) {
- args->thread->renderState().onBitmapDestroyed(args->pixelRefId);
- return nullptr;
-}
-
void RenderProxy::onBitmapDestroyed(uint32_t pixelRefId) {
if (!RenderThread::hasInstance()) return;
- SETUP_TASK(onBitmapDestroyed);
RenderThread& thread = RenderThread::getInstance();
- args->thread = &thread;
- args->pixelRefId = pixelRefId;
- thread.queue(task);
+ thread.queue().post([&thread, pixelRefId]() {
+ thread.renderState().onBitmapDestroyed(pixelRefId);
+ });
}
void RenderProxy::disableVsync() {
Properties::disableVsync = true;
}
-void RenderProxy::post(RenderTask* task) {
- mRenderThread.queue(task);
-}
-
-CREATE_BRIDGE1(repackVectorDrawableAtlas, RenderThread* thread) {
- args->thread->cacheManager().acquireVectorDrawableAtlas()->repackIfNeeded(
- args->thread->getGrContext());
- return nullptr;
-}
-
void RenderProxy::repackVectorDrawableAtlas() {
RenderThread& thread = RenderThread::getInstance();
- SETUP_TASK(repackVectorDrawableAtlas);
- args->thread = &thread;
- thread.queue(task);
-}
-
-CREATE_BRIDGE1(releaseVDAtlasEntries, RenderThread* thread) {
- args->thread->cacheManager().acquireVectorDrawableAtlas()->delayedReleaseEntries();
- return nullptr;
+ thread.queue().post([&thread]() {
+ thread.cacheManager().acquireVectorDrawableAtlas()->repackIfNeeded(thread.getGrContext());
+ });
}
void RenderProxy::releaseVDAtlasEntries() {
RenderThread& thread = RenderThread::getInstance();
- SETUP_TASK(releaseVDAtlasEntries);
- args->thread = &thread;
- thread.queue(task);
-}
-
-void* RenderProxy::postAndWait(MethodInvokeRenderTask* task) {
- void* retval;
- task->setReturnPtr(&retval);
- SignalingRenderTask syncTask(task, &mSyncMutex, &mSyncCondition);
- AutoMutex _lock(mSyncMutex);
- mRenderThread.queue(&syncTask);
- while (!syncTask.hasRun()) {
- mSyncCondition.wait(mSyncMutex);
- }
- return retval;
-}
-
-void* RenderProxy::staticPostAndWait(MethodInvokeRenderTask* task) {
- RenderThread& thread = RenderThread::getInstance();
- LOG_ALWAYS_FATAL_IF(gettid() == thread.getTid());
- void* retval;
- task->setReturnPtr(&retval);
- thread.queueAndWait(task);
- return retval;
+ thread.queue().post([&thread]() {
+ thread.cacheManager().acquireVectorDrawableAtlas()->delayedReleaseEntries();
+ });
}
} /* namespace renderthread */
diff --git a/libs/hwui/renderthread/RenderProxy.h b/libs/hwui/renderthread/RenderProxy.h
index 9440b15..b46d9cc 100644
--- a/libs/hwui/renderthread/RenderProxy.h
+++ b/libs/hwui/renderthread/RenderProxy.h
@@ -17,22 +17,16 @@
#ifndef RENDERPROXY_H_
#define RENDERPROXY_H_
-#include "RenderTask.h"
-
#include <cutils/compiler.h>
-#include <EGL/egl.h>
#include <SkBitmap.h>
-#include <utils/Condition.h>
#include <utils/Functor.h>
-#include <utils/Mutex.h>
-#include <utils/Timers.h>
-#include <utils/StrongPointer.h>
+#include <gui/Surface.h>
-#include "../Caches.h"
#include "../FrameMetricsObserver.h"
#include "../IContextFactory.h"
-#include "CanvasContext.h"
+#include "hwui/Bitmap.h"
#include "DrawFrameTask.h"
+#include "SwapBehavior.h"
namespace android {
class GraphicBuffer;
@@ -41,13 +35,11 @@
class DeferredLayerUpdater;
class RenderNode;
-class DisplayList;
-class Layer;
class Rect;
namespace renderthread {
-class ErrorChannel;
+class CanvasContext;
class RenderThread;
class RenderProxyBridge;
@@ -151,16 +143,8 @@
DrawFrameTask mDrawFrameTask;
- Mutex mSyncMutex;
- Condition mSyncCondition;
-
void destroyContext();
- void post(RenderTask* task);
- void* postAndWait(MethodInvokeRenderTask* task);
-
- static void* staticPostAndWait(MethodInvokeRenderTask* task);
-
// Friend class to help with bridging
friend class RenderProxyBridge;
};
diff --git a/libs/hwui/renderthread/RenderThread.cpp b/libs/hwui/renderthread/RenderThread.cpp
index 51e9374..f3bb120 100644
--- a/libs/hwui/renderthread/RenderThread.cpp
+++ b/libs/hwui/renderthread/RenderThread.cpp
@@ -49,101 +49,6 @@
// Slight delay to give the UI time to push us a new frame before we replay
static const nsecs_t DISPATCH_FRAME_CALLBACKS_DELAY = milliseconds_to_nanoseconds(4);
-TaskQueue::TaskQueue() : mHead(nullptr), mTail(nullptr) {}
-
-RenderTask* TaskQueue::next() {
- RenderTask* ret = mHead;
- if (ret) {
- mHead = ret->mNext;
- if (!mHead) {
- mTail = nullptr;
- }
- ret->mNext = nullptr;
- }
- return ret;
-}
-
-RenderTask* TaskQueue::peek() {
- return mHead;
-}
-
-void TaskQueue::queue(RenderTask* task) {
- // Since the RenderTask itself forms the linked list it is not allowed
- // to have the same task queued twice
- LOG_ALWAYS_FATAL_IF(task->mNext || mTail == task, "Task is already in the queue!");
- if (mTail) {
- // Fast path if we can just append
- if (mTail->mRunAt <= task->mRunAt) {
- mTail->mNext = task;
- mTail = task;
- } else {
- // Need to find the proper insertion point
- RenderTask* previous = nullptr;
- RenderTask* next = mHead;
- while (next && next->mRunAt <= task->mRunAt) {
- previous = next;
- next = next->mNext;
- }
- if (!previous) {
- task->mNext = mHead;
- mHead = task;
- } else {
- previous->mNext = task;
- if (next) {
- task->mNext = next;
- } else {
- mTail = task;
- }
- }
- }
- } else {
- mTail = mHead = task;
- }
-}
-
-void TaskQueue::queueAtFront(RenderTask* task) {
- LOG_ALWAYS_FATAL_IF(task->mNext || mHead == task, "Task is already in the queue!");
- if (mTail) {
- task->mNext = mHead;
- mHead = task;
- } else {
- mTail = mHead = task;
- }
-}
-
-void TaskQueue::remove(RenderTask* task) {
- // TaskQueue is strict here to enforce that users are keeping track of
- // their RenderTasks due to how their memory is managed
- LOG_ALWAYS_FATAL_IF(!task->mNext && mTail != task,
- "Cannot remove a task that isn't in the queue!");
-
- // If task is the head we can just call next() to pop it off
- // Otherwise we need to scan through to find the task before it
- if (peek() == task) {
- next();
- } else {
- RenderTask* previous = mHead;
- while (previous->mNext != task) {
- previous = previous->mNext;
- }
- previous->mNext = task->mNext;
- if (mTail == task) {
- mTail = previous;
- }
- }
-}
-
-class DispatchFrameCallbacks : public RenderTask {
-private:
- RenderThread* mRenderThread;
-public:
- explicit DispatchFrameCallbacks(RenderThread* rt) : mRenderThread(rt) {}
-
- virtual void run() override {
- mRenderThread->dispatchFrameCallbacks();
- }
-};
-
static bool gHasRenderThreadInstance = false;
bool RenderThread::hasInstance() {
@@ -159,19 +64,15 @@
return *sInstance;
}
-RenderThread::RenderThread() : Thread(true)
- , mNextWakeup(LLONG_MAX)
+RenderThread::RenderThread() : ThreadBase()
, mDisplayEventReceiver(nullptr)
, mVsyncRequested(false)
, mFrameCallbackTaskPending(false)
- , mFrameCallbackTask(nullptr)
, mRenderState(nullptr)
, mEglManager(nullptr)
, mVkManager(nullptr) {
Properties::load();
- mFrameCallbackTask = new DispatchFrameCallbacks(this);
- mLooper = new Looper(false);
- run("RenderThread");
+ start("RenderThread");
}
RenderThread::~RenderThread() {
@@ -321,7 +222,9 @@
ATRACE_NAME("queue mFrameCallbackTask");
mFrameCallbackTaskPending = true;
nsecs_t runAt = (vsyncEvent + DISPATCH_FRAME_CALLBACKS_DELAY);
- queueAt(mFrameCallbackTask, runAt);
+ queue().postAt(runAt, [this]() {
+ dispatchFrameCallbacks();
+ });
}
}
}
@@ -356,35 +259,9 @@
setpriority(PRIO_PROCESS, 0, PRIORITY_DISPLAY);
initThreadLocals();
- int timeoutMillis = -1;
- for (;;) {
- int result = mLooper->pollOnce(timeoutMillis);
- LOG_ALWAYS_FATAL_IF(result == Looper::POLL_ERROR,
- "RenderThread Looper POLL_ERROR!");
-
- nsecs_t nextWakeup;
- {
- FatVector<RenderTask*, 10> workQueue;
- // Process our queue, if we have anything. By first acquiring
- // all the pending events then processing them we avoid vsync
- // starvation if more tasks are queued while we are processing tasks.
- while (RenderTask* task = nextTask(&nextWakeup)) {
- workQueue.push_back(task);
- }
- for (auto task : workQueue) {
- task->run();
- // task may have deleted itself, do not reference it again
- }
- }
- if (nextWakeup == LLONG_MAX) {
- timeoutMillis = -1;
- } else {
- nsecs_t timeoutNanos = nextWakeup - systemTime(SYSTEM_TIME_MONOTONIC);
- timeoutMillis = nanoseconds_to_milliseconds(timeoutNanos);
- if (timeoutMillis < 0) {
- timeoutMillis = 0;
- }
- }
+ while (true) {
+ waitForWork();
+ processQueue();
if (mPendingRegistrationFrameCallbacks.size() && !mFrameCallbackTaskPending) {
drainDisplayEventQueue();
@@ -406,46 +283,6 @@
return false;
}
-void RenderThread::queue(RenderTask* task) {
- AutoMutex _lock(mLock);
- mQueue.queue(task);
- if (mNextWakeup && task->mRunAt < mNextWakeup) {
- mNextWakeup = 0;
- mLooper->wake();
- }
-}
-
-void RenderThread::queueAndWait(RenderTask* task) {
- // These need to be local to the thread to avoid the Condition
- // signaling the wrong thread. The easiest way to achieve that is to just
- // make this on the stack, although that has a slight cost to it
- Mutex mutex;
- Condition condition;
- SignalingRenderTask syncTask(task, &mutex, &condition);
-
- AutoMutex _lock(mutex);
- queue(&syncTask);
- while (!syncTask.hasRun()) {
- condition.wait(mutex);
- }
-}
-
-void RenderThread::queueAtFront(RenderTask* task) {
- AutoMutex _lock(mLock);
- mQueue.queueAtFront(task);
- mLooper->wake();
-}
-
-void RenderThread::queueAt(RenderTask* task, nsecs_t runAtNs) {
- task->mRunAt = runAtNs;
- queue(task);
-}
-
-void RenderThread::remove(RenderTask* task) {
- AutoMutex _lock(mLock);
- mQueue.remove(task);
-}
-
void RenderThread::postFrameCallback(IFrameCallback* callback) {
mPendingRegistrationFrameCallbacks.insert(callback);
}
@@ -463,26 +300,6 @@
}
}
-RenderTask* RenderThread::nextTask(nsecs_t* nextWakeup) {
- AutoMutex _lock(mLock);
- RenderTask* next = mQueue.peek();
- if (!next) {
- mNextWakeup = LLONG_MAX;
- } else {
- mNextWakeup = next->mRunAt;
- // Most tasks won't be delayed, so avoid unnecessary systemTime() calls
- if (next->mRunAt <= 0 || next->mRunAt <= systemTime(SYSTEM_TIME_MONOTONIC)) {
- next = mQueue.next();
- } else {
- next = nullptr;
- }
- }
- if (nextWakeup) {
- *nextWakeup = mNextWakeup;
- }
- return next;
-}
-
sk_sp<Bitmap> RenderThread::allocateHardwareBitmap(SkBitmap& skBitmap) {
auto renderType = Properties::getRenderPipelineType();
switch (renderType) {
diff --git a/libs/hwui/renderthread/RenderThread.h b/libs/hwui/renderthread/RenderThread.h
index 30884b5..e1d61c5 100644
--- a/libs/hwui/renderthread/RenderThread.h
+++ b/libs/hwui/renderthread/RenderThread.h
@@ -22,6 +22,7 @@
#include "../JankTracker.h"
#include "CacheManager.h"
#include "TimeLord.h"
+#include "thread/ThreadBase.h"
#include <GrContext.h>
#include <cutils/compiler.h>
@@ -31,7 +32,9 @@
#include <utils/Thread.h>
#include <memory>
+#include <mutex>
#include <set>
+#include <thread/ThreadBase.h>
namespace android {
@@ -47,26 +50,10 @@
namespace renderthread {
class CanvasContext;
-class DispatchFrameCallbacks;
class EglManager;
class RenderProxy;
class VulkanManager;
-class TaskQueue {
-public:
- TaskQueue();
-
- RenderTask* next();
- void queue(RenderTask* task);
- void queueAtFront(RenderTask* task);
- RenderTask* peek();
- void remove(RenderTask* task);
-
-private:
- RenderTask* mHead;
- RenderTask* mTail;
-};
-
// Mimics android.view.Choreographer.FrameCallback
class IFrameCallback {
public:
@@ -76,16 +63,11 @@
~IFrameCallback() {}
};
-class ANDROID_API RenderThread : public Thread {
+class RenderThread : private ThreadBase {
PREVENT_COPY_AND_ASSIGN(RenderThread);
public:
- // RenderThread takes complete ownership of tasks that are queued
- // and will delete them after they are run
- ANDROID_API void queue(RenderTask* task);
- ANDROID_API void queueAndWait(RenderTask* task);
- ANDROID_API void queueAtFront(RenderTask* task);
- void queueAt(RenderTask* task, nsecs_t runAtNs);
- void remove(RenderTask* task);
+
+ WorkQueue& queue() { return ThreadBase::queue(); }
// Mimics android.view.Choreographer
void postFrameCallback(IFrameCallback* callback);
@@ -140,17 +122,6 @@
void dispatchFrameCallbacks();
void requestVsync();
- // Returns the next task to be run. If this returns NULL nextWakeup is set
- // to the time to requery for the nextTask to run. mNextWakeup is also
- // set to this time
- RenderTask* nextTask(nsecs_t* nextWakeup);
-
- sp<Looper> mLooper;
- Mutex mLock;
-
- nsecs_t mNextWakeup;
- TaskQueue mQueue;
-
DisplayInfo mDisplayInfo;
DisplayEventReceiver* mDisplayEventReceiver;
@@ -162,7 +133,6 @@
// the previous one
std::set<IFrameCallback*> mPendingRegistrationFrameCallbacks;
bool mFrameCallbackTaskPending;
- DispatchFrameCallbacks* mFrameCallbackTask;
TimeLord mTimeLord;
RenderState* mRenderState;
diff --git a/libs/hwui/tests/common/TestUtils.h b/libs/hwui/tests/common/TestUtils.h
index f293631..c383fcf 100644
--- a/libs/hwui/tests/common/TestUtils.h
+++ b/libs/hwui/tests/common/TestUtils.h
@@ -318,7 +318,9 @@
*/
static void runOnRenderThread(RtCallback rtCallback) {
TestTask task(rtCallback);
- renderthread::RenderThread::getInstance().queueAndWait(&task);
+ renderthread::RenderThread::getInstance().queue().runSync([&]() {
+ task.run();
+ });
}
static bool isRenderThreadRunning() {
diff --git a/libs/hwui/tests/microbench/TaskManagerBench.cpp b/libs/hwui/tests/microbench/TaskManagerBench.cpp
index cf47f273..67cb428 100644
--- a/libs/hwui/tests/microbench/TaskManagerBench.cpp
+++ b/libs/hwui/tests/microbench/TaskManagerBench.cpp
@@ -19,7 +19,9 @@
#include "thread/Task.h"
#include "thread/TaskManager.h"
#include "thread/TaskProcessor.h"
+#include "thread/ThreadBase.h"
+#include <atomic>
#include <vector>
using namespace android;
@@ -38,6 +40,8 @@
}
};
+class TestThread : public ThreadBase, public virtual RefBase {};
+
void BM_TaskManager_allocateTask(benchmark::State& state) {
std::vector<sp<TrivialTask> > tasks;
tasks.reserve(state.max_iterations);
@@ -86,3 +90,50 @@
state.PauseTiming();
}
BENCHMARK(BM_TaskManager_enqueueRunDeleteTask);
+
+void BM_Thread_enqueueTask(benchmark::State& state) {
+ sp<TestThread> thread{new TestThread};
+ thread->start();
+
+ atomic_int counter(0);
+ int expected = 0;
+ while (state.KeepRunning()) {
+ expected++;
+ thread->queue().post([&counter](){
+ counter++;
+ });
+ }
+ thread->queue().runSync([](){});
+
+ thread->requestExit();
+ thread->join();
+ if (counter != expected) {
+ printf("Ran %d lambads, should have been %d\n", counter.load(), expected);
+ }
+}
+BENCHMARK(BM_Thread_enqueueTask);
+
+void BM_Thread_enqueueRunDeleteTask(benchmark::State& state) {
+ sp<TestThread> thread{new TestThread};
+ thread->start();
+ std::vector<std::future<int>> tasks;
+ tasks.reserve(state.max_iterations);
+
+ int expected = 0;
+ while (state.KeepRunning()) {
+ tasks.emplace_back(thread->queue().async([expected]() -> int {
+ return expected + 1;
+ }));
+ expected++;
+ }
+ state.ResumeTiming();
+ expected = 0;
+ for (auto& future : tasks) {
+ if (future.get() != ++expected) {
+ printf("Mismatch expected %d vs. observed %d\n", expected, future.get());
+ }
+ }
+ tasks.clear();
+ state.PauseTiming();
+}
+BENCHMARK(BM_Thread_enqueueRunDeleteTask);
\ No newline at end of file
diff --git a/libs/hwui/tests/unit/ThreadBaseTests.cpp b/libs/hwui/tests/unit/ThreadBaseTests.cpp
new file mode 100644
index 0000000..7aad348
--- /dev/null
+++ b/libs/hwui/tests/unit/ThreadBaseTests.cpp
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <gtest/gtest.h>
+
+#include "thread/ThreadBase.h"
+#include "utils/TimeUtils.h"
+
+#include <chrono>
+#include "unistd.h"
+
+using namespace android;
+using namespace android::uirenderer;
+
+static ThreadBase& thread() {
+ class TestThread : public ThreadBase, public virtual RefBase {};
+ static sp<TestThread> thread = []() -> auto {
+ sp<TestThread> ret{new TestThread};
+ ret->start("TestThread");
+ return ret;
+ }();
+ return *thread;
+}
+
+static WorkQueue& queue() {
+ return thread().queue();
+}
+
+TEST(ThreadBase, post) {
+ std::atomic_bool ran(false);
+ queue().post([&ran]() {
+ ran = true;
+ });
+ for (int i = 0; !ran && i < 1000; i++) {
+ usleep(1);
+ }
+ ASSERT_TRUE(ran) << "Failed to flip atomic after 1 second";
+}
+
+TEST(ThreadBase, postDelay) {
+ using clock = WorkQueue::clock;
+
+ std::promise<nsecs_t> ranAtPromise;
+ auto queuedAt = clock::now();
+ queue().postDelayed(100_us, [&]() {
+ ranAtPromise.set_value(clock::now());
+ });
+ auto ranAt = ranAtPromise.get_future().get();
+ auto ranAfter = ranAt - queuedAt;
+ ASSERT_TRUE(ranAfter > 90_us) << "Ran after " << ns2us(ranAfter) << "us <= 90us";
+}
+
+TEST(ThreadBase, runSync) {
+ pid_t thisTid = gettid();
+ pid_t otherTid = thisTid;
+
+ auto result = queue().runSync([&otherTid]() -> auto {
+ otherTid = gettid();
+ return 42;
+ });
+
+ ASSERT_EQ(42, result);
+ ASSERT_NE(thisTid, otherTid);
+}
+
+TEST(ThreadBase, async) {
+ pid_t thisTid = gettid();
+ pid_t thisPid = getpid();
+
+ auto otherTid = queue().async([]() -> auto {
+ return gettid();
+ });
+ auto otherPid = queue().async([]() -> auto {
+ return getpid();
+ });
+ auto result = queue().async([]() -> auto {
+ return 42;
+ });
+
+ ASSERT_NE(thisTid, otherTid.get());
+ ASSERT_EQ(thisPid, otherPid.get());
+ ASSERT_EQ(42, result.get());
+}
+
+TEST(ThreadBase, lifecyclePerf) {
+ struct EventCount {
+ std::atomic_int construct{0};
+ std::atomic_int destruct{0};
+ std::atomic_int copy{0};
+ std::atomic_int move{0};
+ };
+
+ struct Counter {
+ Counter(EventCount* count) : mCount(count) {
+ mCount->construct++;
+ }
+
+ Counter(const Counter& other) : mCount(other.mCount) {
+ if (mCount) mCount->copy++;
+ }
+
+ Counter(Counter&& other) : mCount(other.mCount) {
+ other.mCount = nullptr;
+ if (mCount) mCount->move++;
+ }
+
+ Counter& operator=(const Counter& other) {
+ mCount = other.mCount;
+ if (mCount) mCount->copy++;
+ return *this;
+ }
+
+ Counter& operator=(Counter&& other) {
+ mCount = other.mCount;
+ other.mCount = nullptr;
+ if (mCount) mCount->move++;
+ return *this;
+ }
+
+ ~Counter() {
+ if (mCount) mCount->destruct++;
+ }
+
+ EventCount* mCount;
+ };
+
+ EventCount count;
+ {
+ Counter counter{&count};
+ queue().runSync([c = std::move(counter)](){});
+ }
+ ASSERT_EQ(1, count.construct.load());
+ ASSERT_EQ(1, count.destruct.load());
+ ASSERT_EQ(0, count.copy.load());
+ ASSERT_LE(1, count.move.load());
+}
+
+int lifecycleTestHelper(const sp<VirtualLightRefBase>& test) {
+ return queue().runSync([t = test]() -> int {
+ return t->getStrongCount();
+ });
+}
+
+TEST(ThreadBase, lifecycle) {
+ sp<VirtualLightRefBase> dummyObject{new VirtualLightRefBase};
+ ASSERT_EQ(1, dummyObject->getStrongCount());
+ ASSERT_EQ(2, queue().runSync([dummyObject]() -> int {
+ return dummyObject->getStrongCount();
+ }));
+ ASSERT_EQ(1, dummyObject->getStrongCount());
+ ASSERT_EQ(2, lifecycleTestHelper(dummyObject));
+ ASSERT_EQ(1, dummyObject->getStrongCount());
+}
\ No newline at end of file
diff --git a/libs/hwui/thread/ThreadBase.h b/libs/hwui/thread/ThreadBase.h
new file mode 100644
index 0000000..402fd1e
--- /dev/null
+++ b/libs/hwui/thread/ThreadBase.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HWUI_THREADBASE_H
+#define HWUI_THREADBASE_H
+
+#include "WorkQueue.h"
+#include "utils/Macros.h"
+
+#include <utils/Looper.h>
+#include <utils/Thread.h>
+
+#include <algorithm>
+
+namespace android::uirenderer {
+
+class ThreadBase : protected Thread {
+ PREVENT_COPY_AND_ASSIGN(ThreadBase);
+
+public:
+ ThreadBase()
+ : mLooper(new Looper(false))
+ , mQueue([this](){ mLooper->wake(); }, mLock)
+ {}
+
+ WorkQueue& queue() { return mQueue; }
+
+ void requestExit() {
+ Thread::requestExit();
+ mLooper->wake();
+ }
+
+ void start(const char* name = "ThreadBase") {
+ Thread::run(name);
+ }
+
+ void join() {
+ Thread::join();
+ }
+
+protected:
+ void waitForWork() {
+ nsecs_t nextWakeup;
+ {
+ std::unique_lock lock{mLock};
+ nextWakeup = mQueue.nextWakeup(lock);
+ }
+ int timeout = -1;
+ if (nextWakeup < std::numeric_limits<nsecs_t>::max()) {
+ timeout = ns2ms(nextWakeup - WorkQueue::clock::now());
+ if (timeout < 0) timeout = 0;
+ }
+ int result = mLooper->pollOnce(timeout);
+ LOG_ALWAYS_FATAL_IF(result == Looper::POLL_ERROR,
+ "RenderThread Looper POLL_ERROR!");
+ }
+
+ void processQueue() {
+ mQueue.process();
+ }
+
+ virtual bool threadLoop() override {
+ while (!exitPending()) {
+ waitForWork();
+ processQueue();
+ }
+ return false;
+ }
+
+ sp<Looper> mLooper;
+
+private:
+ WorkQueue mQueue;
+ std::mutex mLock;
+};
+
+} // namespace android::uirenderer
+
+
+#endif //HWUI_THREADBASE_H
diff --git a/libs/hwui/thread/WorkQueue.h b/libs/hwui/thread/WorkQueue.h
new file mode 100644
index 0000000..fbb24bb
--- /dev/null
+++ b/libs/hwui/thread/WorkQueue.h
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef HWUI_WORKQUEUE_H
+#define HWUI_WORKQUEUE_H
+
+#include "utils/Macros.h"
+
+#include <log/log.h>
+#include <utils/Timers.h>
+
+#include <condition_variable>
+#include <functional>
+#include <future>
+#include <mutex>
+#include <variant>
+#include <vector>
+
+namespace android::uirenderer {
+
+struct MonotonicClock {
+ static nsecs_t now() { return systemTime(CLOCK_MONOTONIC); }
+};
+
+class WorkQueue {
+ PREVENT_COPY_AND_ASSIGN(WorkQueue);
+public:
+ using clock = MonotonicClock;
+
+private:
+ struct WorkItem {
+ WorkItem() = delete;
+ WorkItem(const WorkItem& other) = delete;
+ WorkItem& operator=(const WorkItem& other) = delete;
+ WorkItem(WorkItem&& other) = default;
+ WorkItem& operator=(WorkItem&& other) = default;
+
+ WorkItem(nsecs_t runAt, std::function<void()>&& work)
+ : runAt(runAt), work(std::move(work)) {}
+
+ nsecs_t runAt;
+ std::function<void()> work;
+ };
+
+public:
+ WorkQueue(std::function<void()>&& wakeFunc, std::mutex& lock)
+ : mWakeFunc(move(wakeFunc))
+ , mLock(lock) {}
+
+ void process() {
+ auto now = clock::now();
+ std::vector<WorkItem> toProcess;
+ {
+ std::unique_lock _lock{mLock};
+ if (mWorkQueue.empty()) return;
+ toProcess = std::move(mWorkQueue);
+ auto moveBack = find_if(std::begin(toProcess), std::end(toProcess),
+ [&now](WorkItem& item) {
+ return item.runAt > now;
+ });
+ if (moveBack != std::end(toProcess)) {
+ mWorkQueue.reserve(std::distance(moveBack, std::end(toProcess)) + 5);
+ std::move(moveBack, std::end(toProcess), std::back_inserter(mWorkQueue));
+ toProcess.erase(moveBack, std::end(toProcess));
+ }
+ }
+ for (auto& item : toProcess) {
+ item.work();
+ }
+ }
+
+ template<class F>
+ void postAt(nsecs_t time, F&& func) {
+ enqueue(WorkItem{time, std::function<void()>(std::forward<F>(func))});
+ }
+
+ template<class F>
+ void postDelayed(nsecs_t delay, F&& func) {
+ enqueue(WorkItem{clock::now() + delay, std::function<void()>(std::forward<F>(func))});
+ }
+
+ template<class F>
+ void post(F&& func) {
+ postAt(0, std::forward<F>(func));
+ }
+
+ template<class F>
+ auto async(F&& func) -> std::future<decltype(func())> {
+ typedef std::packaged_task<decltype(func())()> task_t;
+ auto task = std::make_shared<task_t>(std::forward<F>(func));
+ post([task]() { std::invoke(*task); });
+ return task->get_future();
+ }
+
+ template<class F>
+ auto runSync(F&& func) -> decltype(func()) {
+ std::packaged_task<decltype(func())()> task{std::forward<F>(func)};
+ post([&task]() { std::invoke(task); });
+ return task.get_future().get();
+ };
+
+ nsecs_t nextWakeup(std::unique_lock<std::mutex> &lock) {
+ if (mWorkQueue.empty()) {
+ return std::numeric_limits<nsecs_t>::max();
+ } else {
+ return std::begin(mWorkQueue)->runAt;
+ }
+ }
+
+private:
+ void enqueue(WorkItem&& item) {
+ bool needsWakeup;
+ {
+ std::unique_lock _lock{mLock};
+ auto insertAt = std::find_if(std::begin(mWorkQueue), std::end(mWorkQueue),
+ [time = item.runAt](WorkItem& item) {
+ return item.runAt > time;
+ });
+ needsWakeup = std::begin(mWorkQueue) == insertAt;
+ mWorkQueue.emplace(insertAt, std::move(item));
+ }
+ if (needsWakeup) {
+ mWakeFunc();
+ }
+ }
+
+ std::function<void()> mWakeFunc;
+
+ std::mutex& mLock;
+ std::vector<WorkItem> mWorkQueue;
+};
+
+} // namespace android::uirenderer
+
+#endif //HWUI_WORKQUEUE_H