android_view_ThreadedRenderer.cpp revision aa1735370b24428647508d2ff0f29a617cb955e9
1/*
2 * Copyright (C) 2010 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#define LOG_TAG "ThreadedRenderer"
18
19#include <algorithm>
20#include <atomic>
21
22#include "jni.h"
23#include <nativehelper/JNIHelp.h>
24#include "core_jni_helpers.h"
25#include <GraphicsJNI.h>
26#include <ScopedPrimitiveArray.h>
27
28#include <EGL/egl.h>
29#include <EGL/eglext.h>
30#include <EGL/egl_cache.h>
31
32#include <utils/Looper.h>
33#include <utils/RefBase.h>
34#include <utils/StrongPointer.h>
35#include <utils/Timers.h>
36#include <android_runtime/android_view_Surface.h>
37#include <system/window.h>
38
39#include "android_view_GraphicBuffer.h"
40#include "android_os_MessageQueue.h"
41
42#include <Animator.h>
43#include <AnimationContext.h>
44#include <FrameInfo.h>
45#include <FrameMetricsObserver.h>
46#include <IContextFactory.h>
47#include <JankTracker.h>
48#include <PropertyValuesAnimatorSet.h>
49#include <RenderNode.h>
50#include <renderthread/CanvasContext.h>
51#include <renderthread/RenderProxy.h>
52#include <renderthread/RenderTask.h>
53#include <renderthread/RenderThread.h>
54
55namespace android {
56
57using namespace android::uirenderer;
58using namespace android::uirenderer::renderthread;
59
60struct {
61    jfieldID frameMetrics;
62    jfieldID timingDataBuffer;
63    jfieldID messageQueue;
64    jmethodID callback;
65} gFrameMetricsObserverClassInfo;
66
67static JNIEnv* getenv(JavaVM* vm) {
68    JNIEnv* env;
69    if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
70        LOG_ALWAYS_FATAL("Failed to get JNIEnv for JavaVM: %p", vm);
71    }
72    return env;
73}
74
75// TODO: Clean this up, it's a bit odd to need to call over to
76// rendernode's jni layer. Probably means RootRenderNode should be pulled
77// into HWUI with appropriate callbacks for the various JNI hooks so
78// that RenderNode's JNI layer can handle its own thing
79void onRenderNodeRemoved(JNIEnv* env, RenderNode* node);
80
81class ScopedRemovedRenderNodeObserver : public TreeObserver {
82public:
83    explicit ScopedRemovedRenderNodeObserver(JNIEnv* env) : mEnv(env) {}
84    ~ScopedRemovedRenderNodeObserver() {
85        for (auto& node : mMaybeRemovedNodes) {
86            if (node->hasParents()) continue;
87            onRenderNodeRemoved(mEnv, node.get());
88        }
89    }
90
91    virtual void onMaybeRemovedFromTree(RenderNode* node) override {
92        mMaybeRemovedNodes.insert(sp<RenderNode>(node));
93    }
94
95private:
96    JNIEnv* mEnv;
97    std::set< sp<RenderNode> > mMaybeRemovedNodes;
98};
99
100class OnFinishedEvent {
101public:
102    OnFinishedEvent(BaseRenderNodeAnimator* animator, AnimationListener* listener)
103            : animator(animator), listener(listener) {}
104    sp<BaseRenderNodeAnimator> animator;
105    sp<AnimationListener> listener;
106};
107
108class InvokeAnimationListeners : public MessageHandler {
109public:
110    explicit InvokeAnimationListeners(std::vector<OnFinishedEvent>& events) {
111        mOnFinishedEvents.swap(events);
112    }
113
114    static void callOnFinished(OnFinishedEvent& event) {
115        event.listener->onAnimationFinished(event.animator.get());
116    }
117
118    virtual void handleMessage(const Message& message) {
119        std::for_each(mOnFinishedEvents.begin(), mOnFinishedEvents.end(), callOnFinished);
120        mOnFinishedEvents.clear();
121    }
122
123private:
124    std::vector<OnFinishedEvent> mOnFinishedEvents;
125};
126
127class FinishAndInvokeListener : public MessageHandler {
128public:
129    explicit FinishAndInvokeListener(PropertyValuesAnimatorSet* anim)
130            : mAnimator(anim) {
131        mListener = anim->getOneShotListener();
132        mRequestId = anim->getRequestId();
133    }
134
135    virtual void handleMessage(const Message& message) {
136        if (mAnimator->getRequestId() == mRequestId) {
137            // Request Id has not changed, meaning there's no animation lifecyle change since the
138            // message is posted, so go ahead and call finish to make sure the PlayState is properly
139            // updated. This is needed because before the next frame comes in from UI thread to
140            // trigger an animation update, there could be reverse/cancel etc. So we need to update
141            // the playstate in time to ensure all the subsequent events get chained properly.
142            mAnimator->end();
143        }
144        mListener->onAnimationFinished(nullptr);
145    }
146private:
147    sp<PropertyValuesAnimatorSet> mAnimator;
148    sp<AnimationListener> mListener;
149    uint32_t mRequestId;
150};
151
152class RenderingException : public MessageHandler {
153public:
154    RenderingException(JavaVM* vm, const std::string& message)
155            : mVm(vm)
156            , mMessage(message) {
157    }
158
159    virtual void handleMessage(const Message&) {
160        throwException(mVm, mMessage);
161    }
162
163    static void throwException(JavaVM* vm, const std::string& message) {
164        JNIEnv* env = getenv(vm);
165        jniThrowException(env, "java/lang/IllegalStateException", message.c_str());
166    }
167
168private:
169    JavaVM* mVm;
170    std::string mMessage;
171};
172
173class RootRenderNode : public RenderNode, ErrorHandler {
174public:
175    explicit RootRenderNode(JNIEnv* env) : RenderNode() {
176        mLooper = Looper::getForThread();
177        LOG_ALWAYS_FATAL_IF(!mLooper.get(),
178                "Must create RootRenderNode on a thread with a looper!");
179        env->GetJavaVM(&mVm);
180    }
181
182    virtual ~RootRenderNode() {}
183
184    virtual void onError(const std::string& message) override {
185        mLooper->sendMessage(new RenderingException(mVm, message), 0);
186    }
187
188    virtual void prepareTree(TreeInfo& info) override {
189        info.errorHandler = this;
190
191        for (auto& anim : mVectorDrawableAnimators) {
192            // Assume that the property change in VD from the animators will not be consumed. Mark
193            // otherwise if the VDs are found in the display list tree. For VDs that are not in
194            // the display list tree, we stop providing animation pulses by 1) removing them from
195            // the animation list, 2) post a delayed message to end them at end time so their
196            // listeners can receive the corresponding callbacks.
197            anim->getVectorDrawable()->setPropertyChangeWillBeConsumed(false);
198        }
199        // TODO: This is hacky
200        info.windowInsetLeft = -stagingProperties().getLeft();
201        info.windowInsetTop = -stagingProperties().getTop();
202        info.updateWindowPositions = true;
203        RenderNode::prepareTree(info);
204        info.updateWindowPositions = false;
205        info.windowInsetLeft = 0;
206        info.windowInsetTop = 0;
207        info.errorHandler = nullptr;
208
209        for (auto it = mVectorDrawableAnimators.begin(); it != mVectorDrawableAnimators.end();) {
210            if (!(*it)->getVectorDrawable()->getPropertyChangeWillBeConsumed()) {
211                // Vector Drawable is not in the display list, we should remove this animator from
212                // the list and post a delayed message to end the animator.
213                detachVectorDrawableAnimator(it->get());
214                it = mVectorDrawableAnimators.erase(it);
215            } else {
216                ++it;
217            }
218        }
219        info.out.hasAnimations |= !mVectorDrawableAnimators.empty();
220    }
221
222    void sendMessage(const sp<MessageHandler>& handler) {
223        mLooper->sendMessage(handler, 0);
224    }
225
226    void sendMessageDelayed(const sp<MessageHandler>& handler, nsecs_t delayInMs) {
227        mLooper->sendMessageDelayed(ms2ns(delayInMs), handler, 0);
228    }
229
230    void attachAnimatingNode(RenderNode* animatingNode) {
231        mPendingAnimatingRenderNodes.push_back(animatingNode);
232    }
233
234    void attachPendingVectorDrawableAnimators() {
235        mVectorDrawableAnimators.insert(mPendingVectorDrawableAnimators.begin(),
236                mPendingVectorDrawableAnimators.end());
237        mPendingVectorDrawableAnimators.clear();
238    }
239
240    void detachAnimators() {
241        // Remove animators from the list and post a delayed message in future to end the animator
242        for (auto& anim : mVectorDrawableAnimators) {
243            detachVectorDrawableAnimator(anim.get());
244        }
245        mVectorDrawableAnimators.clear();
246    }
247
248    void doAttachAnimatingNodes(AnimationContext* context) {
249        for (size_t i = 0; i < mPendingAnimatingRenderNodes.size(); i++) {
250            RenderNode* node = mPendingAnimatingRenderNodes[i].get();
251            context->addAnimatingRenderNode(*node);
252        }
253        mPendingAnimatingRenderNodes.clear();
254    }
255
256    void runVectorDrawableAnimators(AnimationContext* context) {
257        for (auto it = mVectorDrawableAnimators.begin(); it != mVectorDrawableAnimators.end();) {
258            if ((*it)->animate(*context)) {
259                it = mVectorDrawableAnimators.erase(it);
260            } else {
261                ++it;
262            }
263        }
264    }
265
266    void pushStagingVectorDrawableAnimators(AnimationContext* context) {
267        for (auto& anim : mVectorDrawableAnimators) {
268            anim->pushStaging(*context);
269        }
270    }
271
272    void destroy() {
273        for (auto& renderNode : mPendingAnimatingRenderNodes) {
274            renderNode->animators().endAllStagingAnimators();
275        }
276        mPendingAnimatingRenderNodes.clear();
277        mPendingVectorDrawableAnimators.clear();
278    }
279
280    void addVectorDrawableAnimator(PropertyValuesAnimatorSet* anim) {
281        mPendingVectorDrawableAnimators.insert(anim);
282    }
283
284private:
285    sp<Looper> mLooper;
286    JavaVM* mVm;
287    std::vector< sp<RenderNode> > mPendingAnimatingRenderNodes;
288    std::set< sp<PropertyValuesAnimatorSet> > mPendingVectorDrawableAnimators;
289    std::set< sp<PropertyValuesAnimatorSet> > mVectorDrawableAnimators;
290    void detachVectorDrawableAnimator(PropertyValuesAnimatorSet* anim) {
291        if (anim->isInfinite() || !anim->isRunning()) {
292            // Do not need to post anything if the animation is infinite (i.e. no meaningful
293            // end listener action), or if the animation has already ended.
294            return;
295        }
296        nsecs_t remainingTimeInMs = anim->getRemainingPlayTime();
297        // Post a delayed onFinished event that is scheduled to be handled when the animator ends.
298        if (anim->getOneShotListener()) {
299            // VectorDrawable's oneshot listener is updated when there are user triggered animation
300            // lifecycle changes, such as start(), end(), etc. By using checking and clearing
301            // one shot listener, we ensure the same end listener event gets posted only once.
302            // Therefore no duplicates. Another benefit of using one shot listener is that no
303            // removal is necessary: the end time of animation will not change unless triggered by
304            // user events, in which case the already posted listener's id will become stale, and
305            // the onFinished callback will then be ignored.
306            sp<FinishAndInvokeListener> message
307                    = new FinishAndInvokeListener(anim);
308            sendMessageDelayed(message, remainingTimeInMs);
309            anim->clearOneShotListener();
310        }
311    }
312};
313
314class AnimationContextBridge : public AnimationContext {
315public:
316    AnimationContextBridge(renderthread::TimeLord& clock, RootRenderNode* rootNode)
317            : AnimationContext(clock), mRootNode(rootNode) {
318    }
319
320    virtual ~AnimationContextBridge() {}
321
322    // Marks the start of a frame, which will update the frame time and move all
323    // next frame animations into the current frame
324    virtual void startFrame(TreeInfo::TraversalMode mode) {
325        if (mode == TreeInfo::MODE_FULL) {
326            mRootNode->doAttachAnimatingNodes(this);
327            mRootNode->attachPendingVectorDrawableAnimators();
328        }
329        AnimationContext::startFrame(mode);
330        // Run VectorDrawable animators in the beginning of the frame instead of during prepareTree,
331        // because one VD can be in multiple render nodes' display list. So it's more simple to
332        // run them all at once before prepareTree than running them or checking whether they have
333        // already ran in each RenderNode. Note that these animators don't damage the RenderNodes.
334        // The damaging is done in prepareTree as needed after checking whether a VD has been
335        // modified.
336        if (mode == TreeInfo::MODE_FULL) {
337            mRootNode->pushStagingVectorDrawableAnimators(this);
338        }
339        mRootNode->runVectorDrawableAnimators(this);
340    }
341
342    // Runs any animations still left in mCurrentFrameAnimations
343    virtual void runRemainingAnimations(TreeInfo& info) {
344        AnimationContext::runRemainingAnimations(info);
345        postOnFinishedEvents();
346    }
347
348    virtual void detachAnimators() override {
349        mRootNode->detachAnimators();
350    }
351
352    virtual void callOnFinished(BaseRenderNodeAnimator* animator, AnimationListener* listener) {
353        OnFinishedEvent event(animator, listener);
354        mOnFinishedEvents.push_back(event);
355    }
356
357    virtual void destroy() {
358        AnimationContext::destroy();
359        detachAnimators();
360        postOnFinishedEvents();
361    }
362
363private:
364    sp<RootRenderNode> mRootNode;
365    std::vector<OnFinishedEvent> mOnFinishedEvents;
366
367    void postOnFinishedEvents() {
368        if (mOnFinishedEvents.size()) {
369            sp<InvokeAnimationListeners> message
370                    = new InvokeAnimationListeners(mOnFinishedEvents);
371            mRootNode->sendMessage(message);
372        }
373    }
374};
375
376class ContextFactoryImpl : public IContextFactory {
377public:
378    explicit ContextFactoryImpl(RootRenderNode* rootNode) : mRootNode(rootNode) {}
379
380    virtual AnimationContext* createAnimationContext(renderthread::TimeLord& clock) {
381        return new AnimationContextBridge(clock, mRootNode);
382    }
383
384private:
385    RootRenderNode* mRootNode;
386};
387
388class ObserverProxy;
389
390class NotifyHandler : public MessageHandler {
391public:
392    NotifyHandler(JavaVM* vm, ObserverProxy* observer) : mVm(vm), mObserver(observer) {}
393
394    virtual void handleMessage(const Message& message);
395
396private:
397    JavaVM* const mVm;
398    ObserverProxy* const mObserver;
399};
400
401static jlongArray get_metrics_buffer(JNIEnv* env, jobject observer) {
402    jobject frameMetrics = env->GetObjectField(
403            observer, gFrameMetricsObserverClassInfo.frameMetrics);
404    LOG_ALWAYS_FATAL_IF(frameMetrics == nullptr, "unable to retrieve data sink object");
405    jobject buffer = env->GetObjectField(
406            frameMetrics, gFrameMetricsObserverClassInfo.timingDataBuffer);
407    LOG_ALWAYS_FATAL_IF(buffer == nullptr, "unable to retrieve data sink buffer");
408    return reinterpret_cast<jlongArray>(buffer);
409}
410
411/*
412 * Implements JNI layer for hwui frame metrics reporting.
413 */
414class ObserverProxy : public FrameMetricsObserver {
415public:
416    ObserverProxy(JavaVM *vm, jobject observer) : mVm(vm) {
417        JNIEnv* env = getenv(mVm);
418
419        mObserverWeak = env->NewWeakGlobalRef(observer);
420        LOG_ALWAYS_FATAL_IF(mObserverWeak == nullptr,
421                "unable to create frame stats observer reference");
422
423        jlongArray buffer = get_metrics_buffer(env, observer);
424        jsize bufferSize = env->GetArrayLength(reinterpret_cast<jarray>(buffer));
425        LOG_ALWAYS_FATAL_IF(bufferSize != kBufferSize,
426                "Mismatched Java/Native FrameMetrics data format.");
427
428        jobject messageQueueLocal = env->GetObjectField(
429                observer, gFrameMetricsObserverClassInfo.messageQueue);
430        mMessageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueLocal);
431        LOG_ALWAYS_FATAL_IF(mMessageQueue == nullptr, "message queue not available");
432
433        mMessageHandler = new NotifyHandler(mVm, this);
434        LOG_ALWAYS_FATAL_IF(mMessageHandler == nullptr,
435                "OOM: unable to allocate NotifyHandler");
436    }
437
438    ~ObserverProxy() {
439        JNIEnv* env = getenv(mVm);
440        env->DeleteWeakGlobalRef(mObserverWeak);
441    }
442
443    jweak getObserverReference() {
444        return mObserverWeak;
445    }
446
447    bool getNextBuffer(JNIEnv* env, jlongArray sink, int* dropCount) {
448        FrameMetricsNotification& elem = mRingBuffer[mNextInQueue];
449
450        if (elem.hasData.load()) {
451            env->SetLongArrayRegion(sink, 0, kBufferSize, elem.buffer);
452            *dropCount = elem.dropCount;
453            mNextInQueue = (mNextInQueue + 1) % kRingSize;
454            elem.hasData = false;
455            return true;
456        }
457
458        return false;
459    }
460
461    virtual void notify(const int64_t* stats) {
462        FrameMetricsNotification& elem = mRingBuffer[mNextFree];
463
464        if (!elem.hasData.load()) {
465            memcpy(elem.buffer, stats, kBufferSize * sizeof(stats[0]));
466
467            elem.dropCount = mDroppedReports;
468            mDroppedReports = 0;
469
470            incStrong(nullptr);
471            mNextFree = (mNextFree + 1) % kRingSize;
472            elem.hasData = true;
473
474            mMessageQueue->getLooper()->sendMessage(mMessageHandler, mMessage);
475        } else {
476            mDroppedReports++;
477        }
478    }
479
480private:
481    static const int kBufferSize = static_cast<int>(FrameInfoIndex::NumIndexes);
482    static constexpr int kRingSize = 3;
483
484    class FrameMetricsNotification {
485    public:
486        FrameMetricsNotification() : hasData(false) {}
487
488        std::atomic_bool hasData;
489        int64_t buffer[kBufferSize];
490        int dropCount = 0;
491    };
492
493    JavaVM* const mVm;
494    jweak mObserverWeak;
495
496    sp<MessageQueue> mMessageQueue;
497    sp<NotifyHandler> mMessageHandler;
498    Message mMessage;
499
500    int mNextFree = 0;
501    int mNextInQueue = 0;
502    FrameMetricsNotification mRingBuffer[kRingSize];
503
504    int mDroppedReports = 0;
505};
506
507void NotifyHandler::handleMessage(const Message& message) {
508    JNIEnv* env = getenv(mVm);
509
510    jobject target = env->NewLocalRef(mObserver->getObserverReference());
511
512    if (target != nullptr) {
513        jlongArray javaBuffer = get_metrics_buffer(env, target);
514        int dropCount = 0;
515        while (mObserver->getNextBuffer(env, javaBuffer, &dropCount)) {
516            env->CallVoidMethod(target, gFrameMetricsObserverClassInfo.callback, dropCount);
517        }
518        env->DeleteLocalRef(target);
519    }
520
521    mObserver->decStrong(nullptr);
522}
523
524static jboolean android_view_ThreadedRenderer_supportsOpenGL(JNIEnv* env, jobject clazz) {
525    char prop[PROPERTY_VALUE_MAX];
526    if (property_get("ro.kernel.qemu", prop, NULL) == 0) {
527        // not in the emulator
528        return JNI_TRUE;
529    }
530    // In the emulator this property will be set > 0 when OpenGL ES 2.0 is
531    // enabled, 0 otherwise. On old emulator versions it will be undefined.
532    property_get("qemu.gles", prop, "0");
533    return atoi(prop) > 0 ? JNI_TRUE : JNI_FALSE;
534}
535
536static void android_view_ThreadedRenderer_setAtlas(JNIEnv* env, jobject clazz,
537        jlong proxyPtr, jobject graphicBuffer, jlongArray atlasMapArray) {
538    sp<GraphicBuffer> buffer = graphicBufferForJavaObject(env, graphicBuffer);
539    jsize len = env->GetArrayLength(atlasMapArray);
540    if (len <= 0) {
541        ALOGW("Failed to initialize atlas, invalid map length: %d", len);
542        return;
543    }
544    int64_t* map = new int64_t[len];
545    env->GetLongArrayRegion(atlasMapArray, 0, len, map);
546
547    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
548    proxy->setTextureAtlas(buffer, map, len);
549}
550
551static void android_view_ThreadedRenderer_setProcessStatsBuffer(JNIEnv* env, jobject clazz,
552        jlong proxyPtr, jint fd) {
553    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
554    proxy->setProcessStatsBuffer(fd);
555}
556
557static jint android_view_ThreadedRenderer_getRenderThreadTid(JNIEnv* env, jobject clazz,
558        jlong proxyPtr) {
559    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
560    return proxy->getRenderThreadTid();
561}
562
563static jlong android_view_ThreadedRenderer_createRootRenderNode(JNIEnv* env, jobject clazz) {
564    RootRenderNode* node = new RootRenderNode(env);
565    node->incStrong(0);
566    node->setName("RootRenderNode");
567    return reinterpret_cast<jlong>(node);
568}
569
570static jlong android_view_ThreadedRenderer_createProxy(JNIEnv* env, jobject clazz,
571        jboolean translucent, jlong rootRenderNodePtr) {
572    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootRenderNodePtr);
573    ContextFactoryImpl factory(rootRenderNode);
574    return (jlong) new RenderProxy(translucent, rootRenderNode, &factory);
575}
576
577static void android_view_ThreadedRenderer_deleteProxy(JNIEnv* env, jobject clazz,
578        jlong proxyPtr) {
579    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
580    delete proxy;
581}
582
583static jboolean android_view_ThreadedRenderer_loadSystemProperties(JNIEnv* env, jobject clazz,
584        jlong proxyPtr) {
585    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
586    return proxy->loadSystemProperties();
587}
588
589static void android_view_ThreadedRenderer_setName(JNIEnv* env, jobject clazz,
590        jlong proxyPtr, jstring jname) {
591    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
592    const char* name = env->GetStringUTFChars(jname, NULL);
593    proxy->setName(name);
594    env->ReleaseStringUTFChars(jname, name);
595}
596
597static void android_view_ThreadedRenderer_initialize(JNIEnv* env, jobject clazz,
598        jlong proxyPtr, jobject jsurface) {
599    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
600    sp<Surface> surface = android_view_Surface_getSurface(env, jsurface);
601    proxy->initialize(surface);
602}
603
604static void android_view_ThreadedRenderer_updateSurface(JNIEnv* env, jobject clazz,
605        jlong proxyPtr, jobject jsurface) {
606    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
607    sp<Surface> surface;
608    if (jsurface) {
609        surface = android_view_Surface_getSurface(env, jsurface);
610    }
611    proxy->updateSurface(surface);
612}
613
614static jboolean android_view_ThreadedRenderer_pauseSurface(JNIEnv* env, jobject clazz,
615        jlong proxyPtr, jobject jsurface) {
616    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
617    sp<Surface> surface;
618    if (jsurface) {
619        surface = android_view_Surface_getSurface(env, jsurface);
620    }
621    return proxy->pauseSurface(surface);
622}
623
624static void android_view_ThreadedRenderer_setStopped(JNIEnv* env, jobject clazz,
625        jlong proxyPtr, jboolean stopped) {
626    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
627    proxy->setStopped(stopped);
628}
629
630static void android_view_ThreadedRenderer_setup(JNIEnv* env, jobject clazz, jlong proxyPtr,
631        jfloat lightRadius, jint ambientShadowAlpha, jint spotShadowAlpha) {
632    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
633    proxy->setup(lightRadius, ambientShadowAlpha, spotShadowAlpha);
634}
635
636static void android_view_ThreadedRenderer_setLightCenter(JNIEnv* env, jobject clazz,
637        jlong proxyPtr, jfloat lightX, jfloat lightY, jfloat lightZ) {
638    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
639    proxy->setLightCenter((Vector3){lightX, lightY, lightZ});
640}
641
642static void android_view_ThreadedRenderer_setOpaque(JNIEnv* env, jobject clazz,
643        jlong proxyPtr, jboolean opaque) {
644    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
645    proxy->setOpaque(opaque);
646}
647
648static int android_view_ThreadedRenderer_syncAndDrawFrame(JNIEnv* env, jobject clazz,
649        jlong proxyPtr, jlongArray frameInfo, jint frameInfoSize) {
650    LOG_ALWAYS_FATAL_IF(frameInfoSize != UI_THREAD_FRAME_INFO_SIZE,
651            "Mismatched size expectations, given %d expected %d",
652            frameInfoSize, UI_THREAD_FRAME_INFO_SIZE);
653    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
654    ScopedRemovedRenderNodeObserver observer(env);
655    env->GetLongArrayRegion(frameInfo, 0, frameInfoSize, proxy->frameInfo());
656    return proxy->syncAndDrawFrame(&observer);
657}
658
659static void android_view_ThreadedRenderer_destroy(JNIEnv* env, jobject clazz,
660        jlong proxyPtr, jlong rootNodePtr) {
661    ScopedRemovedRenderNodeObserver observer(env);
662    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr);
663    rootRenderNode->destroy();
664    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
665    proxy->destroy(&observer);
666}
667
668static void android_view_ThreadedRenderer_registerAnimatingRenderNode(JNIEnv* env, jobject clazz,
669        jlong rootNodePtr, jlong animatingNodePtr) {
670    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr);
671    RenderNode* animatingNode = reinterpret_cast<RenderNode*>(animatingNodePtr);
672    rootRenderNode->attachAnimatingNode(animatingNode);
673}
674
675static void android_view_ThreadedRenderer_registerVectorDrawableAnimator(JNIEnv* env, jobject clazz,
676        jlong rootNodePtr, jlong animatorPtr) {
677    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr);
678    PropertyValuesAnimatorSet* animator = reinterpret_cast<PropertyValuesAnimatorSet*>(animatorPtr);
679    rootRenderNode->addVectorDrawableAnimator(animator);
680}
681
682static void android_view_ThreadedRenderer_invokeFunctor(JNIEnv* env, jobject clazz,
683        jlong functorPtr, jboolean waitForCompletion) {
684    Functor* functor = reinterpret_cast<Functor*>(functorPtr);
685    RenderProxy::invokeFunctor(functor, waitForCompletion);
686}
687
688static jlong android_view_ThreadedRenderer_createTextureLayer(JNIEnv* env, jobject clazz,
689        jlong proxyPtr) {
690    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
691    DeferredLayerUpdater* layer = proxy->createTextureLayer();
692    return reinterpret_cast<jlong>(layer);
693}
694
695static void android_view_ThreadedRenderer_buildLayer(JNIEnv* env, jobject clazz,
696        jlong proxyPtr, jlong nodePtr) {
697    ScopedRemovedRenderNodeObserver observer(env);
698    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
699    RenderNode* node = reinterpret_cast<RenderNode*>(nodePtr);
700    proxy->buildLayer(node, &observer);
701}
702
703static jboolean android_view_ThreadedRenderer_copyLayerInto(JNIEnv* env, jobject clazz,
704        jlong proxyPtr, jlong layerPtr, jobject jbitmap) {
705    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
706    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
707    SkBitmap bitmap;
708    GraphicsJNI::getSkBitmap(env, jbitmap, &bitmap);
709    return proxy->copyLayerInto(layer, bitmap);
710}
711
712static void android_view_ThreadedRenderer_pushLayerUpdate(JNIEnv* env, jobject clazz,
713        jlong proxyPtr, jlong layerPtr) {
714    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
715    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
716    proxy->pushLayerUpdate(layer);
717}
718
719static void android_view_ThreadedRenderer_cancelLayerUpdate(JNIEnv* env, jobject clazz,
720        jlong proxyPtr, jlong layerPtr) {
721    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
722    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
723    proxy->cancelLayerUpdate(layer);
724}
725
726static void android_view_ThreadedRenderer_detachSurfaceTexture(JNIEnv* env, jobject clazz,
727        jlong proxyPtr, jlong layerPtr) {
728    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
729    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
730    proxy->detachSurfaceTexture(layer);
731}
732
733static void android_view_ThreadedRenderer_destroyHardwareResources(JNIEnv* env, jobject clazz,
734        jlong proxyPtr) {
735    ScopedRemovedRenderNodeObserver observer(env);
736    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
737    proxy->destroyHardwareResources(&observer);
738}
739
740static void android_view_ThreadedRenderer_trimMemory(JNIEnv* env, jobject clazz,
741        jint level) {
742    RenderProxy::trimMemory(level);
743}
744
745static void android_view_ThreadedRenderer_overrideProperty(JNIEnv* env, jobject clazz,
746        jstring name, jstring value) {
747    const char* nameCharArray = env->GetStringUTFChars(name, NULL);
748    const char* valueCharArray = env->GetStringUTFChars(value, NULL);
749    RenderProxy::overrideProperty(nameCharArray, valueCharArray);
750    env->ReleaseStringUTFChars(name, nameCharArray);
751    env->ReleaseStringUTFChars(name, valueCharArray);
752}
753
754static void android_view_ThreadedRenderer_fence(JNIEnv* env, jobject clazz,
755        jlong proxyPtr) {
756    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
757    proxy->fence();
758}
759
760static void android_view_ThreadedRenderer_stopDrawing(JNIEnv* env, jobject clazz,
761        jlong proxyPtr) {
762    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
763    proxy->stopDrawing();
764}
765
766static void android_view_ThreadedRenderer_notifyFramePending(JNIEnv* env, jobject clazz,
767        jlong proxyPtr) {
768    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
769    proxy->notifyFramePending();
770}
771
772static void android_view_ThreadedRenderer_serializeDisplayListTree(JNIEnv* env, jobject clazz,
773        jlong proxyPtr) {
774    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
775    proxy->serializeDisplayListTree();
776}
777
778static void android_view_ThreadedRenderer_dumpProfileInfo(JNIEnv* env, jobject clazz,
779        jlong proxyPtr, jobject javaFileDescriptor, jint dumpFlags) {
780    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
781    int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor);
782    proxy->dumpProfileInfo(fd, dumpFlags);
783}
784
785static void android_view_ThreadedRenderer_dumpProfileData(JNIEnv* env, jobject clazz,
786        jbyteArray jdata, jobject javaFileDescriptor) {
787    int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor);
788    ScopedByteArrayRO buffer(env, jdata);
789    if (buffer.get()) {
790        JankTracker::dumpBuffer(buffer.get(), buffer.size(), fd);
791    }
792}
793
794static void android_view_ThreadedRenderer_addRenderNode(JNIEnv* env, jobject clazz,
795        jlong proxyPtr, jlong renderNodePtr, jboolean placeFront) {
796    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
797    RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
798    proxy->addRenderNode(renderNode, placeFront);
799}
800
801static void android_view_ThreadedRenderer_removeRenderNode(JNIEnv* env, jobject clazz,
802        jlong proxyPtr, jlong renderNodePtr) {
803    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
804    RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
805    proxy->removeRenderNode(renderNode);
806}
807
808static void android_view_ThreadedRendererd_drawRenderNode(JNIEnv* env, jobject clazz,
809        jlong proxyPtr, jlong renderNodePtr) {
810    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
811    RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
812    proxy->drawRenderNode(renderNode);
813}
814
815static void android_view_ThreadedRenderer_setContentDrawBounds(JNIEnv* env,
816        jobject clazz, jlong proxyPtr, jint left, jint top, jint right, jint bottom) {
817    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
818    proxy->setContentDrawBounds(left, top, right, bottom);
819}
820
821static jint android_view_ThreadedRenderer_copySurfaceInto(JNIEnv* env,
822        jobject clazz, jobject jsurface, jobject jbitmap) {
823    SkBitmap bitmap;
824    GraphicsJNI::getSkBitmap(env, jbitmap, &bitmap);
825    sp<Surface> surface = android_view_Surface_getSurface(env, jsurface);
826    return RenderProxy::copySurfaceInto(surface, &bitmap);
827}
828
829// ----------------------------------------------------------------------------
830// FrameMetricsObserver
831// ----------------------------------------------------------------------------
832
833static jlong android_view_ThreadedRenderer_addFrameMetricsObserver(JNIEnv* env,
834        jclass clazz, jlong proxyPtr, jobject fso) {
835    JavaVM* vm = nullptr;
836    if (env->GetJavaVM(&vm) != JNI_OK) {
837        LOG_ALWAYS_FATAL("Unable to get Java VM");
838        return 0;
839    }
840
841    renderthread::RenderProxy* renderProxy =
842            reinterpret_cast<renderthread::RenderProxy*>(proxyPtr);
843
844    FrameMetricsObserver* observer = new ObserverProxy(vm, fso);
845    renderProxy->addFrameMetricsObserver(observer);
846    return reinterpret_cast<jlong>(observer);
847}
848
849static void android_view_ThreadedRenderer_removeFrameMetricsObserver(JNIEnv* env, jclass clazz,
850        jlong proxyPtr, jlong observerPtr) {
851    FrameMetricsObserver* observer = reinterpret_cast<FrameMetricsObserver*>(observerPtr);
852    renderthread::RenderProxy* renderProxy =
853            reinterpret_cast<renderthread::RenderProxy*>(proxyPtr);
854
855    renderProxy->removeFrameMetricsObserver(observer);
856}
857
858// ----------------------------------------------------------------------------
859// Shaders
860// ----------------------------------------------------------------------------
861
862static void android_view_ThreadedRenderer_setupShadersDiskCache(JNIEnv* env, jobject clazz,
863        jstring diskCachePath) {
864    const char* cacheArray = env->GetStringUTFChars(diskCachePath, NULL);
865    egl_cache_t::get()->setCacheFilename(cacheArray);
866    env->ReleaseStringUTFChars(diskCachePath, cacheArray);
867}
868
869// ----------------------------------------------------------------------------
870// JNI Glue
871// ----------------------------------------------------------------------------
872
873const char* const kClassPathName = "android/view/ThreadedRenderer";
874
875static const JNINativeMethod gMethods[] = {
876    { "nSupportsOpenGL", "!()Z", (void*) android_view_ThreadedRenderer_supportsOpenGL },
877    { "nSetAtlas", "(JLandroid/view/GraphicBuffer;[J)V",   (void*) android_view_ThreadedRenderer_setAtlas },
878    { "nSetProcessStatsBuffer", "(JI)V", (void*) android_view_ThreadedRenderer_setProcessStatsBuffer },
879    { "nGetRenderThreadTid", "(J)I", (void*) android_view_ThreadedRenderer_getRenderThreadTid },
880    { "nCreateRootRenderNode", "()J", (void*) android_view_ThreadedRenderer_createRootRenderNode },
881    { "nCreateProxy", "(ZJ)J", (void*) android_view_ThreadedRenderer_createProxy },
882    { "nDeleteProxy", "(J)V", (void*) android_view_ThreadedRenderer_deleteProxy },
883    { "nLoadSystemProperties", "(J)Z", (void*) android_view_ThreadedRenderer_loadSystemProperties },
884    { "nSetName", "(JLjava/lang/String;)V", (void*) android_view_ThreadedRenderer_setName },
885    { "nInitialize", "(JLandroid/view/Surface;)V", (void*) android_view_ThreadedRenderer_initialize },
886    { "nUpdateSurface", "(JLandroid/view/Surface;)V", (void*) android_view_ThreadedRenderer_updateSurface },
887    { "nPauseSurface", "(JLandroid/view/Surface;)Z", (void*) android_view_ThreadedRenderer_pauseSurface },
888    { "nSetStopped", "(JZ)V", (void*) android_view_ThreadedRenderer_setStopped },
889    { "nSetup", "(JFII)V", (void*) android_view_ThreadedRenderer_setup },
890    { "nSetLightCenter", "(JFFF)V", (void*) android_view_ThreadedRenderer_setLightCenter },
891    { "nSetOpaque", "(JZ)V", (void*) android_view_ThreadedRenderer_setOpaque },
892    { "nSyncAndDrawFrame", "(J[JI)I", (void*) android_view_ThreadedRenderer_syncAndDrawFrame },
893    { "nDestroy", "(JJ)V", (void*) android_view_ThreadedRenderer_destroy },
894    { "nRegisterAnimatingRenderNode", "(JJ)V", (void*) android_view_ThreadedRenderer_registerAnimatingRenderNode },
895    { "nRegisterVectorDrawableAnimator", "(JJ)V", (void*) android_view_ThreadedRenderer_registerVectorDrawableAnimator },
896    { "nInvokeFunctor", "(JZ)V", (void*) android_view_ThreadedRenderer_invokeFunctor },
897    { "nCreateTextureLayer", "(J)J", (void*) android_view_ThreadedRenderer_createTextureLayer },
898    { "nBuildLayer", "(JJ)V", (void*) android_view_ThreadedRenderer_buildLayer },
899    { "nCopyLayerInto", "(JJLandroid/graphics/Bitmap;)Z", (void*) android_view_ThreadedRenderer_copyLayerInto },
900    { "nPushLayerUpdate", "(JJ)V", (void*) android_view_ThreadedRenderer_pushLayerUpdate },
901    { "nCancelLayerUpdate", "(JJ)V", (void*) android_view_ThreadedRenderer_cancelLayerUpdate },
902    { "nDetachSurfaceTexture", "(JJ)V", (void*) android_view_ThreadedRenderer_detachSurfaceTexture },
903    { "nDestroyHardwareResources", "(J)V", (void*) android_view_ThreadedRenderer_destroyHardwareResources },
904    { "nTrimMemory", "(I)V", (void*) android_view_ThreadedRenderer_trimMemory },
905    { "nOverrideProperty", "(Ljava/lang/String;Ljava/lang/String;)V",  (void*) android_view_ThreadedRenderer_overrideProperty },
906    { "nFence", "(J)V", (void*) android_view_ThreadedRenderer_fence },
907    { "nStopDrawing", "(J)V", (void*) android_view_ThreadedRenderer_stopDrawing },
908    { "nNotifyFramePending", "(J)V", (void*) android_view_ThreadedRenderer_notifyFramePending },
909    { "nSerializeDisplayListTree", "(J)V", (void*) android_view_ThreadedRenderer_serializeDisplayListTree },
910    { "nDumpProfileInfo", "(JLjava/io/FileDescriptor;I)V", (void*) android_view_ThreadedRenderer_dumpProfileInfo },
911    { "nDumpProfileData", "([BLjava/io/FileDescriptor;)V", (void*) android_view_ThreadedRenderer_dumpProfileData },
912    { "setupShadersDiskCache", "(Ljava/lang/String;)V",
913                (void*) android_view_ThreadedRenderer_setupShadersDiskCache },
914    { "nAddRenderNode", "(JJZ)V", (void*) android_view_ThreadedRenderer_addRenderNode},
915    { "nRemoveRenderNode", "(JJ)V", (void*) android_view_ThreadedRenderer_removeRenderNode},
916    { "nDrawRenderNode", "(JJ)V", (void*) android_view_ThreadedRendererd_drawRenderNode},
917    { "nSetContentDrawBounds", "(JIIII)V", (void*)android_view_ThreadedRenderer_setContentDrawBounds},
918    { "nAddFrameMetricsObserver",
919            "(JLandroid/view/FrameMetricsObserver;)J",
920            (void*)android_view_ThreadedRenderer_addFrameMetricsObserver },
921    { "nRemoveFrameMetricsObserver",
922            "(JJ)V",
923            (void*)android_view_ThreadedRenderer_removeFrameMetricsObserver },
924    { "nCopySurfaceInto", "(Landroid/view/Surface;Landroid/graphics/Bitmap;)I",
925                (void*)android_view_ThreadedRenderer_copySurfaceInto },
926};
927
928int register_android_view_ThreadedRenderer(JNIEnv* env) {
929    jclass observerClass = FindClassOrDie(env, "android/view/FrameMetricsObserver");
930    gFrameMetricsObserverClassInfo.frameMetrics = GetFieldIDOrDie(
931            env, observerClass, "mFrameMetrics", "Landroid/view/FrameMetrics;");
932    gFrameMetricsObserverClassInfo.messageQueue = GetFieldIDOrDie(
933            env, observerClass, "mMessageQueue", "Landroid/os/MessageQueue;");
934    gFrameMetricsObserverClassInfo.callback = GetMethodIDOrDie(
935            env, observerClass, "notifyDataAvailable", "(I)V");
936
937    jclass metricsClass = FindClassOrDie(env, "android/view/FrameMetrics");
938    gFrameMetricsObserverClassInfo.timingDataBuffer = GetFieldIDOrDie(
939            env, metricsClass, "mTimingData", "[J");
940
941    return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
942}
943
944}; // namespace android
945