android_view_ThreadedRenderer.cpp revision 6ccb38bb130b5637e7bdbce7d3b2b646b9401bcd
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 : mRunningVDAnimators) {
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            // Mark the VD dirty so it will damage itself during prepareTree.
199            anim->getVectorDrawable()->markDirty();
200        }
201        if (info.mode == TreeInfo::MODE_FULL) {
202            for (auto &anim : mPausedVDAnimators) {
203                anim->getVectorDrawable()->setPropertyChangeWillBeConsumed(false);
204                anim->getVectorDrawable()->markDirty();
205            }
206        }
207        // TODO: This is hacky
208        info.windowInsetLeft = -stagingProperties().getLeft();
209        info.windowInsetTop = -stagingProperties().getTop();
210        info.updateWindowPositions = true;
211        RenderNode::prepareTree(info);
212        info.updateWindowPositions = false;
213        info.windowInsetLeft = 0;
214        info.windowInsetTop = 0;
215        info.errorHandler = nullptr;
216    }
217
218    void sendMessage(const sp<MessageHandler>& handler) {
219        mLooper->sendMessage(handler, 0);
220    }
221
222    void sendMessageDelayed(const sp<MessageHandler>& handler, nsecs_t delayInMs) {
223        mLooper->sendMessageDelayed(ms2ns(delayInMs), handler, 0);
224    }
225
226    void attachAnimatingNode(RenderNode* animatingNode) {
227        mPendingAnimatingRenderNodes.push_back(animatingNode);
228    }
229
230    void attachPendingVectorDrawableAnimators() {
231        mRunningVDAnimators.insert(mPendingVectorDrawableAnimators.begin(),
232                mPendingVectorDrawableAnimators.end());
233        mPendingVectorDrawableAnimators.clear();
234    }
235
236    void detachAnimators() {
237        // Remove animators from the list and post a delayed message in future to end the animator
238        for (auto& anim : mRunningVDAnimators) {
239            detachVectorDrawableAnimator(anim.get());
240        }
241        mRunningVDAnimators.clear();
242        mPausedVDAnimators.clear();
243    }
244
245    // Move all the animators to the paused list, and send a delayed message to notify the finished
246    // listener.
247    void pauseAnimators() {
248        mPausedVDAnimators.insert(mRunningVDAnimators.begin(), mRunningVDAnimators.end());
249        for (auto& anim : mRunningVDAnimators) {
250            detachVectorDrawableAnimator(anim.get());
251        }
252        mRunningVDAnimators.clear();
253    }
254
255    void doAttachAnimatingNodes(AnimationContext* context) {
256        for (size_t i = 0; i < mPendingAnimatingRenderNodes.size(); i++) {
257            RenderNode* node = mPendingAnimatingRenderNodes[i].get();
258            context->addAnimatingRenderNode(*node);
259        }
260        mPendingAnimatingRenderNodes.clear();
261    }
262
263    // Run VectorDrawable animators after prepareTree.
264    void runVectorDrawableAnimators(AnimationContext* context, TreeInfo& info) {
265        // Push staging.
266        if (info.mode == TreeInfo::MODE_FULL) {
267            pushStagingVectorDrawableAnimators(context);
268        }
269
270        // Run the animators in the running list.
271        for (auto it = mRunningVDAnimators.begin(); it != mRunningVDAnimators.end();) {
272            if ((*it)->animate(*context)) {
273                it = mRunningVDAnimators.erase(it);
274            } else {
275                it++;
276            }
277        }
278
279        // Run the animators in paused list during full sync.
280        if (info.mode == TreeInfo::MODE_FULL) {
281            // During full sync we also need to pulse paused animators, in case their targets
282            // have been added back to the display list. All the animators that passed the
283            // scheduled finish time will be removed from the paused list.
284            for (auto it = mPausedVDAnimators.begin(); it != mPausedVDAnimators.end();) {
285                if ((*it)->animate(*context)) {
286                    // Animator has finished, remove from the list.
287                    it = mPausedVDAnimators.erase(it);
288                } else {
289                    it++;
290                }
291            }
292        }
293
294        // Move the animators with a target not in DisplayList to paused list.
295        for (auto it = mRunningVDAnimators.begin(); it != mRunningVDAnimators.end();) {
296            if (!(*it)->getVectorDrawable()->getPropertyChangeWillBeConsumed()) {
297                // Vector Drawable is not in the display list, we should remove this animator from
298                // the list, put it in the paused list, and post a delayed message to end the
299                // animator.
300                detachVectorDrawableAnimator(it->get());
301                mPausedVDAnimators.insert(*it);
302                it = mRunningVDAnimators.erase(it);
303            } else {
304                it++;
305            }
306        }
307
308        // Move the animators with a target in DisplayList from paused list to running list, and
309        // trim paused list.
310        if (info.mode == TreeInfo::MODE_FULL) {
311            // Check whether any paused animator's target is back in Display List. If so, put the
312            // animator back in the running list.
313            for (auto it = mPausedVDAnimators.begin(); it != mPausedVDAnimators.end();) {
314                if ((*it)->getVectorDrawable()->getPropertyChangeWillBeConsumed()) {
315                    mRunningVDAnimators.insert(*it);
316                    it = mPausedVDAnimators.erase(it);
317                } else {
318                    it++;
319                }
320            }
321            // Trim paused VD animators at full sync, so that when Java loses reference to an
322            // animator, we know we won't be requested to animate it any more, then we remove such
323            // animators from the paused list so they can be properly freed. We also remove the
324            // animators from paused list when the time elapsed since start has exceeded duration.
325            trimPausedVDAnimators(context);
326        }
327
328        info.out.hasAnimations |= !mRunningVDAnimators.empty();
329    }
330
331    void trimPausedVDAnimators(AnimationContext* context) {
332        // Trim paused vector drawable animator list.
333        for (auto it = mPausedVDAnimators.begin(); it != mPausedVDAnimators.end();) {
334            // Remove paused VD animator if no one else is referencing it. Note that animators that
335            // have passed scheduled finish time are removed from list when they are being pulsed
336            // before prepare tree.
337            // TODO: this is a bit hacky, need to figure out a better way to track when the paused
338            // animators should be freed.
339            if ((*it)->getStrongCount() == 1) {
340                it = mPausedVDAnimators.erase(it);
341            } else {
342                it++;
343            }
344        }
345    }
346
347    void pushStagingVectorDrawableAnimators(AnimationContext* context) {
348        for (auto& anim : mRunningVDAnimators) {
349            anim->pushStaging(*context);
350        }
351    }
352
353    void destroy() {
354        for (auto& renderNode : mPendingAnimatingRenderNodes) {
355            renderNode->animators().endAllStagingAnimators();
356        }
357        mPendingAnimatingRenderNodes.clear();
358        mPendingVectorDrawableAnimators.clear();
359    }
360
361    void addVectorDrawableAnimator(PropertyValuesAnimatorSet* anim) {
362        mPendingVectorDrawableAnimators.insert(anim);
363    }
364
365private:
366    sp<Looper> mLooper;
367    JavaVM* mVm;
368    std::vector< sp<RenderNode> > mPendingAnimatingRenderNodes;
369    std::set< sp<PropertyValuesAnimatorSet> > mPendingVectorDrawableAnimators;
370    std::set< sp<PropertyValuesAnimatorSet> > mRunningVDAnimators;
371    // mPausedVDAnimators stores a list of animators that have not yet passed the finish time, but
372    // their VectorDrawable targets are no longer in the DisplayList. We skip these animators when
373    // render thread runs animators independent of UI thread (i.e. RT_ONLY mode). These animators
374    // need to be re-activated once their VD target is added back into DisplayList. Since that could
375    // only happen when we do a full sync, we need to make sure to pulse these paused animators at
376    // full sync. If any animator's VD target is found in DisplayList during a full sync, we move
377    // the animator back to the running list.
378    std::set< sp<PropertyValuesAnimatorSet> > mPausedVDAnimators;
379    void detachVectorDrawableAnimator(PropertyValuesAnimatorSet* anim) {
380        if (anim->isInfinite() || !anim->isRunning()) {
381            // Do not need to post anything if the animation is infinite (i.e. no meaningful
382            // end listener action), or if the animation has already ended.
383            return;
384        }
385        nsecs_t remainingTimeInMs = anim->getRemainingPlayTime();
386        // Post a delayed onFinished event that is scheduled to be handled when the animator ends.
387        if (anim->getOneShotListener()) {
388            // VectorDrawable's oneshot listener is updated when there are user triggered animation
389            // lifecycle changes, such as start(), end(), etc. By using checking and clearing
390            // one shot listener, we ensure the same end listener event gets posted only once.
391            // Therefore no duplicates. Another benefit of using one shot listener is that no
392            // removal is necessary: the end time of animation will not change unless triggered by
393            // user events, in which case the already posted listener's id will become stale, and
394            // the onFinished callback will then be ignored.
395            sp<FinishAndInvokeListener> message
396                    = new FinishAndInvokeListener(anim);
397            sendMessageDelayed(message, remainingTimeInMs);
398            anim->clearOneShotListener();
399        }
400    }
401};
402
403class AnimationContextBridge : public AnimationContext {
404public:
405    AnimationContextBridge(renderthread::TimeLord& clock, RootRenderNode* rootNode)
406            : AnimationContext(clock), mRootNode(rootNode) {
407    }
408
409    virtual ~AnimationContextBridge() {}
410
411    // Marks the start of a frame, which will update the frame time and move all
412    // next frame animations into the current frame
413    virtual void startFrame(TreeInfo::TraversalMode mode) {
414        if (mode == TreeInfo::MODE_FULL) {
415            mRootNode->doAttachAnimatingNodes(this);
416            mRootNode->attachPendingVectorDrawableAnimators();
417        }
418        AnimationContext::startFrame(mode);
419    }
420
421    // Runs any animations still left in mCurrentFrameAnimations
422    virtual void runRemainingAnimations(TreeInfo& info) {
423        AnimationContext::runRemainingAnimations(info);
424        mRootNode->runVectorDrawableAnimators(this, info);
425        postOnFinishedEvents();
426    }
427
428    virtual void pauseAnimators() override {
429        mRootNode->pauseAnimators();
430    }
431
432    virtual void callOnFinished(BaseRenderNodeAnimator* animator, AnimationListener* listener) {
433        OnFinishedEvent event(animator, listener);
434        mOnFinishedEvents.push_back(event);
435    }
436
437    virtual void destroy() {
438        AnimationContext::destroy();
439        mRootNode->detachAnimators();
440        postOnFinishedEvents();
441    }
442
443private:
444    sp<RootRenderNode> mRootNode;
445    std::vector<OnFinishedEvent> mOnFinishedEvents;
446
447    void postOnFinishedEvents() {
448        if (mOnFinishedEvents.size()) {
449            sp<InvokeAnimationListeners> message
450                    = new InvokeAnimationListeners(mOnFinishedEvents);
451            mRootNode->sendMessage(message);
452        }
453    }
454};
455
456class ContextFactoryImpl : public IContextFactory {
457public:
458    explicit ContextFactoryImpl(RootRenderNode* rootNode) : mRootNode(rootNode) {}
459
460    virtual AnimationContext* createAnimationContext(renderthread::TimeLord& clock) {
461        return new AnimationContextBridge(clock, mRootNode);
462    }
463
464private:
465    RootRenderNode* mRootNode;
466};
467
468class ObserverProxy;
469
470class NotifyHandler : public MessageHandler {
471public:
472    NotifyHandler(JavaVM* vm, ObserverProxy* observer) : mVm(vm), mObserver(observer) {}
473
474    virtual void handleMessage(const Message& message);
475
476private:
477    JavaVM* const mVm;
478    ObserverProxy* const mObserver;
479};
480
481static jlongArray get_metrics_buffer(JNIEnv* env, jobject observer) {
482    jobject frameMetrics = env->GetObjectField(
483            observer, gFrameMetricsObserverClassInfo.frameMetrics);
484    LOG_ALWAYS_FATAL_IF(frameMetrics == nullptr, "unable to retrieve data sink object");
485    jobject buffer = env->GetObjectField(
486            frameMetrics, gFrameMetricsObserverClassInfo.timingDataBuffer);
487    LOG_ALWAYS_FATAL_IF(buffer == nullptr, "unable to retrieve data sink buffer");
488    return reinterpret_cast<jlongArray>(buffer);
489}
490
491/*
492 * Implements JNI layer for hwui frame metrics reporting.
493 */
494class ObserverProxy : public FrameMetricsObserver {
495public:
496    ObserverProxy(JavaVM *vm, jobject observer) : mVm(vm) {
497        JNIEnv* env = getenv(mVm);
498
499        mObserverWeak = env->NewWeakGlobalRef(observer);
500        LOG_ALWAYS_FATAL_IF(mObserverWeak == nullptr,
501                "unable to create frame stats observer reference");
502
503        jlongArray buffer = get_metrics_buffer(env, observer);
504        jsize bufferSize = env->GetArrayLength(reinterpret_cast<jarray>(buffer));
505        LOG_ALWAYS_FATAL_IF(bufferSize != kBufferSize,
506                "Mismatched Java/Native FrameMetrics data format.");
507
508        jobject messageQueueLocal = env->GetObjectField(
509                observer, gFrameMetricsObserverClassInfo.messageQueue);
510        mMessageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueLocal);
511        LOG_ALWAYS_FATAL_IF(mMessageQueue == nullptr, "message queue not available");
512
513        mMessageHandler = new NotifyHandler(mVm, this);
514        LOG_ALWAYS_FATAL_IF(mMessageHandler == nullptr,
515                "OOM: unable to allocate NotifyHandler");
516    }
517
518    ~ObserverProxy() {
519        JNIEnv* env = getenv(mVm);
520        env->DeleteWeakGlobalRef(mObserverWeak);
521    }
522
523    jweak getObserverReference() {
524        return mObserverWeak;
525    }
526
527    bool getNextBuffer(JNIEnv* env, jlongArray sink, int* dropCount) {
528        FrameMetricsNotification& elem = mRingBuffer[mNextInQueue];
529
530        if (elem.hasData.load()) {
531            env->SetLongArrayRegion(sink, 0, kBufferSize, elem.buffer);
532            *dropCount = elem.dropCount;
533            mNextInQueue = (mNextInQueue + 1) % kRingSize;
534            elem.hasData = false;
535            return true;
536        }
537
538        return false;
539    }
540
541    virtual void notify(const int64_t* stats) {
542        FrameMetricsNotification& elem = mRingBuffer[mNextFree];
543
544        if (!elem.hasData.load()) {
545            memcpy(elem.buffer, stats, kBufferSize * sizeof(stats[0]));
546
547            elem.dropCount = mDroppedReports;
548            mDroppedReports = 0;
549
550            incStrong(nullptr);
551            mNextFree = (mNextFree + 1) % kRingSize;
552            elem.hasData = true;
553
554            mMessageQueue->getLooper()->sendMessage(mMessageHandler, mMessage);
555        } else {
556            mDroppedReports++;
557        }
558    }
559
560private:
561    static const int kBufferSize = static_cast<int>(FrameInfoIndex::NumIndexes);
562    static constexpr int kRingSize = 3;
563
564    class FrameMetricsNotification {
565    public:
566        FrameMetricsNotification() : hasData(false) {}
567
568        std::atomic_bool hasData;
569        int64_t buffer[kBufferSize];
570        int dropCount = 0;
571    };
572
573    JavaVM* const mVm;
574    jweak mObserverWeak;
575
576    sp<MessageQueue> mMessageQueue;
577    sp<NotifyHandler> mMessageHandler;
578    Message mMessage;
579
580    int mNextFree = 0;
581    int mNextInQueue = 0;
582    FrameMetricsNotification mRingBuffer[kRingSize];
583
584    int mDroppedReports = 0;
585};
586
587void NotifyHandler::handleMessage(const Message& message) {
588    JNIEnv* env = getenv(mVm);
589
590    jobject target = env->NewLocalRef(mObserver->getObserverReference());
591
592    if (target != nullptr) {
593        jlongArray javaBuffer = get_metrics_buffer(env, target);
594        int dropCount = 0;
595        while (mObserver->getNextBuffer(env, javaBuffer, &dropCount)) {
596            env->CallVoidMethod(target, gFrameMetricsObserverClassInfo.callback, dropCount);
597        }
598        env->DeleteLocalRef(target);
599    }
600
601    mObserver->decStrong(nullptr);
602}
603
604static jboolean android_view_ThreadedRenderer_supportsOpenGL(JNIEnv* env, jobject clazz) {
605    char prop[PROPERTY_VALUE_MAX];
606    if (property_get("ro.kernel.qemu", prop, NULL) == 0) {
607        // not in the emulator
608        return JNI_TRUE;
609    }
610    // In the emulator this property will be set > 0 when OpenGL ES 2.0 is
611    // enabled, 0 otherwise. On old emulator versions it will be undefined.
612    property_get("qemu.gles", prop, "0");
613    return atoi(prop) > 0 ? JNI_TRUE : JNI_FALSE;
614}
615
616static void android_view_ThreadedRenderer_setAtlas(JNIEnv* env, jobject clazz,
617        jlong proxyPtr, jobject graphicBuffer, jlongArray atlasMapArray) {
618    sp<GraphicBuffer> buffer = graphicBufferForJavaObject(env, graphicBuffer);
619    jsize len = env->GetArrayLength(atlasMapArray);
620    if (len <= 0) {
621        ALOGW("Failed to initialize atlas, invalid map length: %d", len);
622        return;
623    }
624    int64_t* map = new int64_t[len];
625    env->GetLongArrayRegion(atlasMapArray, 0, len, map);
626
627    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
628    proxy->setTextureAtlas(buffer, map, len);
629}
630
631static void android_view_ThreadedRenderer_setProcessStatsBuffer(JNIEnv* env, jobject clazz,
632        jlong proxyPtr, jint fd) {
633    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
634    proxy->setProcessStatsBuffer(fd);
635}
636
637static jint android_view_ThreadedRenderer_getRenderThreadTid(JNIEnv* env, jobject clazz,
638        jlong proxyPtr) {
639    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
640    return proxy->getRenderThreadTid();
641}
642
643static jlong android_view_ThreadedRenderer_createRootRenderNode(JNIEnv* env, jobject clazz) {
644    RootRenderNode* node = new RootRenderNode(env);
645    node->incStrong(0);
646    node->setName("RootRenderNode");
647    return reinterpret_cast<jlong>(node);
648}
649
650static jlong android_view_ThreadedRenderer_createProxy(JNIEnv* env, jobject clazz,
651        jboolean translucent, jlong rootRenderNodePtr) {
652    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootRenderNodePtr);
653    ContextFactoryImpl factory(rootRenderNode);
654    return (jlong) new RenderProxy(translucent, rootRenderNode, &factory);
655}
656
657static void android_view_ThreadedRenderer_deleteProxy(JNIEnv* env, jobject clazz,
658        jlong proxyPtr) {
659    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
660    delete proxy;
661}
662
663static jboolean android_view_ThreadedRenderer_loadSystemProperties(JNIEnv* env, jobject clazz,
664        jlong proxyPtr) {
665    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
666    return proxy->loadSystemProperties();
667}
668
669static void android_view_ThreadedRenderer_setName(JNIEnv* env, jobject clazz,
670        jlong proxyPtr, jstring jname) {
671    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
672    const char* name = env->GetStringUTFChars(jname, NULL);
673    proxy->setName(name);
674    env->ReleaseStringUTFChars(jname, name);
675}
676
677static void android_view_ThreadedRenderer_initialize(JNIEnv* env, jobject clazz,
678        jlong proxyPtr, jobject jsurface) {
679    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
680    sp<Surface> surface = android_view_Surface_getSurface(env, jsurface);
681    proxy->initialize(surface);
682}
683
684static void android_view_ThreadedRenderer_updateSurface(JNIEnv* env, jobject clazz,
685        jlong proxyPtr, jobject jsurface) {
686    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
687    sp<Surface> surface;
688    if (jsurface) {
689        surface = android_view_Surface_getSurface(env, jsurface);
690    }
691    proxy->updateSurface(surface);
692}
693
694static jboolean android_view_ThreadedRenderer_pauseSurface(JNIEnv* env, jobject clazz,
695        jlong proxyPtr, jobject jsurface) {
696    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
697    sp<Surface> surface;
698    if (jsurface) {
699        surface = android_view_Surface_getSurface(env, jsurface);
700    }
701    return proxy->pauseSurface(surface);
702}
703
704static void android_view_ThreadedRenderer_setStopped(JNIEnv* env, jobject clazz,
705        jlong proxyPtr, jboolean stopped) {
706    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
707    proxy->setStopped(stopped);
708}
709
710static void android_view_ThreadedRenderer_setup(JNIEnv* env, jobject clazz, jlong proxyPtr,
711        jfloat lightRadius, jint ambientShadowAlpha, jint spotShadowAlpha) {
712    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
713    proxy->setup(lightRadius, ambientShadowAlpha, spotShadowAlpha);
714}
715
716static void android_view_ThreadedRenderer_setLightCenter(JNIEnv* env, jobject clazz,
717        jlong proxyPtr, jfloat lightX, jfloat lightY, jfloat lightZ) {
718    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
719    proxy->setLightCenter((Vector3){lightX, lightY, lightZ});
720}
721
722static void android_view_ThreadedRenderer_setOpaque(JNIEnv* env, jobject clazz,
723        jlong proxyPtr, jboolean opaque) {
724    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
725    proxy->setOpaque(opaque);
726}
727
728static int android_view_ThreadedRenderer_syncAndDrawFrame(JNIEnv* env, jobject clazz,
729        jlong proxyPtr, jlongArray frameInfo, jint frameInfoSize) {
730    LOG_ALWAYS_FATAL_IF(frameInfoSize != UI_THREAD_FRAME_INFO_SIZE,
731            "Mismatched size expectations, given %d expected %d",
732            frameInfoSize, UI_THREAD_FRAME_INFO_SIZE);
733    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
734    ScopedRemovedRenderNodeObserver observer(env);
735    env->GetLongArrayRegion(frameInfo, 0, frameInfoSize, proxy->frameInfo());
736    return proxy->syncAndDrawFrame(&observer);
737}
738
739static void android_view_ThreadedRenderer_destroy(JNIEnv* env, jobject clazz,
740        jlong proxyPtr, jlong rootNodePtr) {
741    ScopedRemovedRenderNodeObserver observer(env);
742    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr);
743    rootRenderNode->destroy();
744    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
745    proxy->destroy(&observer);
746}
747
748static void android_view_ThreadedRenderer_registerAnimatingRenderNode(JNIEnv* env, jobject clazz,
749        jlong rootNodePtr, jlong animatingNodePtr) {
750    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr);
751    RenderNode* animatingNode = reinterpret_cast<RenderNode*>(animatingNodePtr);
752    rootRenderNode->attachAnimatingNode(animatingNode);
753}
754
755static void android_view_ThreadedRenderer_registerVectorDrawableAnimator(JNIEnv* env, jobject clazz,
756        jlong rootNodePtr, jlong animatorPtr) {
757    RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr);
758    PropertyValuesAnimatorSet* animator = reinterpret_cast<PropertyValuesAnimatorSet*>(animatorPtr);
759    rootRenderNode->addVectorDrawableAnimator(animator);
760}
761
762static void android_view_ThreadedRenderer_invokeFunctor(JNIEnv* env, jobject clazz,
763        jlong functorPtr, jboolean waitForCompletion) {
764    Functor* functor = reinterpret_cast<Functor*>(functorPtr);
765    RenderProxy::invokeFunctor(functor, waitForCompletion);
766}
767
768static jlong android_view_ThreadedRenderer_createTextureLayer(JNIEnv* env, jobject clazz,
769        jlong proxyPtr) {
770    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
771    DeferredLayerUpdater* layer = proxy->createTextureLayer();
772    return reinterpret_cast<jlong>(layer);
773}
774
775static void android_view_ThreadedRenderer_buildLayer(JNIEnv* env, jobject clazz,
776        jlong proxyPtr, jlong nodePtr) {
777    ScopedRemovedRenderNodeObserver observer(env);
778    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
779    RenderNode* node = reinterpret_cast<RenderNode*>(nodePtr);
780    proxy->buildLayer(node, &observer);
781}
782
783static jboolean android_view_ThreadedRenderer_copyLayerInto(JNIEnv* env, jobject clazz,
784        jlong proxyPtr, jlong layerPtr, jobject jbitmap) {
785    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
786    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
787    SkBitmap bitmap;
788    GraphicsJNI::getSkBitmap(env, jbitmap, &bitmap);
789    return proxy->copyLayerInto(layer, bitmap);
790}
791
792static void android_view_ThreadedRenderer_pushLayerUpdate(JNIEnv* env, jobject clazz,
793        jlong proxyPtr, jlong layerPtr) {
794    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
795    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
796    proxy->pushLayerUpdate(layer);
797}
798
799static void android_view_ThreadedRenderer_cancelLayerUpdate(JNIEnv* env, jobject clazz,
800        jlong proxyPtr, jlong layerPtr) {
801    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
802    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
803    proxy->cancelLayerUpdate(layer);
804}
805
806static void android_view_ThreadedRenderer_detachSurfaceTexture(JNIEnv* env, jobject clazz,
807        jlong proxyPtr, jlong layerPtr) {
808    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
809    DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr);
810    proxy->detachSurfaceTexture(layer);
811}
812
813static void android_view_ThreadedRenderer_destroyHardwareResources(JNIEnv* env, jobject clazz,
814        jlong proxyPtr) {
815    ScopedRemovedRenderNodeObserver observer(env);
816    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
817    proxy->destroyHardwareResources(&observer);
818}
819
820static void android_view_ThreadedRenderer_trimMemory(JNIEnv* env, jobject clazz,
821        jint level) {
822    RenderProxy::trimMemory(level);
823}
824
825static void android_view_ThreadedRenderer_overrideProperty(JNIEnv* env, jobject clazz,
826        jstring name, jstring value) {
827    const char* nameCharArray = env->GetStringUTFChars(name, NULL);
828    const char* valueCharArray = env->GetStringUTFChars(value, NULL);
829    RenderProxy::overrideProperty(nameCharArray, valueCharArray);
830    env->ReleaseStringUTFChars(name, nameCharArray);
831    env->ReleaseStringUTFChars(name, valueCharArray);
832}
833
834static void android_view_ThreadedRenderer_fence(JNIEnv* env, jobject clazz,
835        jlong proxyPtr) {
836    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
837    proxy->fence();
838}
839
840static void android_view_ThreadedRenderer_stopDrawing(JNIEnv* env, jobject clazz,
841        jlong proxyPtr) {
842    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
843    proxy->stopDrawing();
844}
845
846static void android_view_ThreadedRenderer_notifyFramePending(JNIEnv* env, jobject clazz,
847        jlong proxyPtr) {
848    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
849    proxy->notifyFramePending();
850}
851
852static void android_view_ThreadedRenderer_serializeDisplayListTree(JNIEnv* env, jobject clazz,
853        jlong proxyPtr) {
854    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
855    proxy->serializeDisplayListTree();
856}
857
858static void android_view_ThreadedRenderer_dumpProfileInfo(JNIEnv* env, jobject clazz,
859        jlong proxyPtr, jobject javaFileDescriptor, jint dumpFlags) {
860    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
861    int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor);
862    proxy->dumpProfileInfo(fd, dumpFlags);
863}
864
865static void android_view_ThreadedRenderer_dumpProfileData(JNIEnv* env, jobject clazz,
866        jbyteArray jdata, jobject javaFileDescriptor) {
867    int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor);
868    ScopedByteArrayRO buffer(env, jdata);
869    if (buffer.get()) {
870        JankTracker::dumpBuffer(buffer.get(), buffer.size(), fd);
871    }
872}
873
874static void android_view_ThreadedRenderer_addRenderNode(JNIEnv* env, jobject clazz,
875        jlong proxyPtr, jlong renderNodePtr, jboolean placeFront) {
876    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
877    RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
878    proxy->addRenderNode(renderNode, placeFront);
879}
880
881static void android_view_ThreadedRenderer_removeRenderNode(JNIEnv* env, jobject clazz,
882        jlong proxyPtr, jlong renderNodePtr) {
883    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
884    RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
885    proxy->removeRenderNode(renderNode);
886}
887
888static void android_view_ThreadedRendererd_drawRenderNode(JNIEnv* env, jobject clazz,
889        jlong proxyPtr, jlong renderNodePtr) {
890    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
891    RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
892    proxy->drawRenderNode(renderNode);
893}
894
895static void android_view_ThreadedRenderer_setContentDrawBounds(JNIEnv* env,
896        jobject clazz, jlong proxyPtr, jint left, jint top, jint right, jint bottom) {
897    RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr);
898    proxy->setContentDrawBounds(left, top, right, bottom);
899}
900
901static jint android_view_ThreadedRenderer_copySurfaceInto(JNIEnv* env,
902        jobject clazz, jobject jsurface, jint left, jint top,
903        jint right, jint bottom, jobject jbitmap) {
904    SkBitmap bitmap;
905    GraphicsJNI::getSkBitmap(env, jbitmap, &bitmap);
906    sp<Surface> surface = android_view_Surface_getSurface(env, jsurface);
907    return RenderProxy::copySurfaceInto(surface, left, top, right, bottom, &bitmap);
908}
909
910// ----------------------------------------------------------------------------
911// FrameMetricsObserver
912// ----------------------------------------------------------------------------
913
914static jlong android_view_ThreadedRenderer_addFrameMetricsObserver(JNIEnv* env,
915        jclass clazz, jlong proxyPtr, jobject fso) {
916    JavaVM* vm = nullptr;
917    if (env->GetJavaVM(&vm) != JNI_OK) {
918        LOG_ALWAYS_FATAL("Unable to get Java VM");
919        return 0;
920    }
921
922    renderthread::RenderProxy* renderProxy =
923            reinterpret_cast<renderthread::RenderProxy*>(proxyPtr);
924
925    FrameMetricsObserver* observer = new ObserverProxy(vm, fso);
926    renderProxy->addFrameMetricsObserver(observer);
927    return reinterpret_cast<jlong>(observer);
928}
929
930static void android_view_ThreadedRenderer_removeFrameMetricsObserver(JNIEnv* env, jclass clazz,
931        jlong proxyPtr, jlong observerPtr) {
932    FrameMetricsObserver* observer = reinterpret_cast<FrameMetricsObserver*>(observerPtr);
933    renderthread::RenderProxy* renderProxy =
934            reinterpret_cast<renderthread::RenderProxy*>(proxyPtr);
935
936    renderProxy->removeFrameMetricsObserver(observer);
937}
938
939// ----------------------------------------------------------------------------
940// Shaders
941// ----------------------------------------------------------------------------
942
943static void android_view_ThreadedRenderer_setupShadersDiskCache(JNIEnv* env, jobject clazz,
944        jstring diskCachePath) {
945    const char* cacheArray = env->GetStringUTFChars(diskCachePath, NULL);
946    egl_cache_t::get()->setCacheFilename(cacheArray);
947    env->ReleaseStringUTFChars(diskCachePath, cacheArray);
948}
949
950// ----------------------------------------------------------------------------
951// JNI Glue
952// ----------------------------------------------------------------------------
953
954const char* const kClassPathName = "android/view/ThreadedRenderer";
955
956static const JNINativeMethod gMethods[] = {
957    { "nSupportsOpenGL", "()Z", (void*) android_view_ThreadedRenderer_supportsOpenGL },
958    { "nSetAtlas", "(JLandroid/view/GraphicBuffer;[J)V",   (void*) android_view_ThreadedRenderer_setAtlas },
959    { "nSetProcessStatsBuffer", "(JI)V", (void*) android_view_ThreadedRenderer_setProcessStatsBuffer },
960    { "nGetRenderThreadTid", "(J)I", (void*) android_view_ThreadedRenderer_getRenderThreadTid },
961    { "nCreateRootRenderNode", "()J", (void*) android_view_ThreadedRenderer_createRootRenderNode },
962    { "nCreateProxy", "(ZJ)J", (void*) android_view_ThreadedRenderer_createProxy },
963    { "nDeleteProxy", "(J)V", (void*) android_view_ThreadedRenderer_deleteProxy },
964    { "nLoadSystemProperties", "(J)Z", (void*) android_view_ThreadedRenderer_loadSystemProperties },
965    { "nSetName", "(JLjava/lang/String;)V", (void*) android_view_ThreadedRenderer_setName },
966    { "nInitialize", "(JLandroid/view/Surface;)V", (void*) android_view_ThreadedRenderer_initialize },
967    { "nUpdateSurface", "(JLandroid/view/Surface;)V", (void*) android_view_ThreadedRenderer_updateSurface },
968    { "nPauseSurface", "(JLandroid/view/Surface;)Z", (void*) android_view_ThreadedRenderer_pauseSurface },
969    { "nSetStopped", "(JZ)V", (void*) android_view_ThreadedRenderer_setStopped },
970    { "nSetup", "(JFII)V", (void*) android_view_ThreadedRenderer_setup },
971    { "nSetLightCenter", "(JFFF)V", (void*) android_view_ThreadedRenderer_setLightCenter },
972    { "nSetOpaque", "(JZ)V", (void*) android_view_ThreadedRenderer_setOpaque },
973    { "nSyncAndDrawFrame", "(J[JI)I", (void*) android_view_ThreadedRenderer_syncAndDrawFrame },
974    { "nDestroy", "(JJ)V", (void*) android_view_ThreadedRenderer_destroy },
975    { "nRegisterAnimatingRenderNode", "(JJ)V", (void*) android_view_ThreadedRenderer_registerAnimatingRenderNode },
976    { "nRegisterVectorDrawableAnimator", "(JJ)V", (void*) android_view_ThreadedRenderer_registerVectorDrawableAnimator },
977    { "nInvokeFunctor", "(JZ)V", (void*) android_view_ThreadedRenderer_invokeFunctor },
978    { "nCreateTextureLayer", "(J)J", (void*) android_view_ThreadedRenderer_createTextureLayer },
979    { "nBuildLayer", "(JJ)V", (void*) android_view_ThreadedRenderer_buildLayer },
980    { "nCopyLayerInto", "(JJLandroid/graphics/Bitmap;)Z", (void*) android_view_ThreadedRenderer_copyLayerInto },
981    { "nPushLayerUpdate", "(JJ)V", (void*) android_view_ThreadedRenderer_pushLayerUpdate },
982    { "nCancelLayerUpdate", "(JJ)V", (void*) android_view_ThreadedRenderer_cancelLayerUpdate },
983    { "nDetachSurfaceTexture", "(JJ)V", (void*) android_view_ThreadedRenderer_detachSurfaceTexture },
984    { "nDestroyHardwareResources", "(J)V", (void*) android_view_ThreadedRenderer_destroyHardwareResources },
985    { "nTrimMemory", "(I)V", (void*) android_view_ThreadedRenderer_trimMemory },
986    { "nOverrideProperty", "(Ljava/lang/String;Ljava/lang/String;)V",  (void*) android_view_ThreadedRenderer_overrideProperty },
987    { "nFence", "(J)V", (void*) android_view_ThreadedRenderer_fence },
988    { "nStopDrawing", "(J)V", (void*) android_view_ThreadedRenderer_stopDrawing },
989    { "nNotifyFramePending", "(J)V", (void*) android_view_ThreadedRenderer_notifyFramePending },
990    { "nSerializeDisplayListTree", "(J)V", (void*) android_view_ThreadedRenderer_serializeDisplayListTree },
991    { "nDumpProfileInfo", "(JLjava/io/FileDescriptor;I)V", (void*) android_view_ThreadedRenderer_dumpProfileInfo },
992    { "nDumpProfileData", "([BLjava/io/FileDescriptor;)V", (void*) android_view_ThreadedRenderer_dumpProfileData },
993    { "setupShadersDiskCache", "(Ljava/lang/String;)V",
994                (void*) android_view_ThreadedRenderer_setupShadersDiskCache },
995    { "nAddRenderNode", "(JJZ)V", (void*) android_view_ThreadedRenderer_addRenderNode},
996    { "nRemoveRenderNode", "(JJ)V", (void*) android_view_ThreadedRenderer_removeRenderNode},
997    { "nDrawRenderNode", "(JJ)V", (void*) android_view_ThreadedRendererd_drawRenderNode},
998    { "nSetContentDrawBounds", "(JIIII)V", (void*)android_view_ThreadedRenderer_setContentDrawBounds},
999    { "nAddFrameMetricsObserver",
1000            "(JLandroid/view/FrameMetricsObserver;)J",
1001            (void*)android_view_ThreadedRenderer_addFrameMetricsObserver },
1002    { "nRemoveFrameMetricsObserver",
1003            "(JJ)V",
1004            (void*)android_view_ThreadedRenderer_removeFrameMetricsObserver },
1005    { "nCopySurfaceInto", "(Landroid/view/Surface;IIIILandroid/graphics/Bitmap;)I",
1006                (void*)android_view_ThreadedRenderer_copySurfaceInto },
1007};
1008
1009int register_android_view_ThreadedRenderer(JNIEnv* env) {
1010    jclass observerClass = FindClassOrDie(env, "android/view/FrameMetricsObserver");
1011    gFrameMetricsObserverClassInfo.frameMetrics = GetFieldIDOrDie(
1012            env, observerClass, "mFrameMetrics", "Landroid/view/FrameMetrics;");
1013    gFrameMetricsObserverClassInfo.messageQueue = GetFieldIDOrDie(
1014            env, observerClass, "mMessageQueue", "Landroid/os/MessageQueue;");
1015    gFrameMetricsObserverClassInfo.callback = GetMethodIDOrDie(
1016            env, observerClass, "notifyDataAvailable", "(I)V");
1017
1018    jclass metricsClass = FindClassOrDie(env, "android/view/FrameMetrics");
1019    gFrameMetricsObserverClassInfo.timingDataBuffer = GetFieldIDOrDie(
1020            env, metricsClass, "mTimingData", "[J");
1021
1022    return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods));
1023}
1024
1025}; // namespace android
1026