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 55 namespace android { 56 57 using namespace android::uirenderer; 58 using namespace android::uirenderer::renderthread; 59 60 struct { 61 jfieldID frameMetrics; 62 jfieldID timingDataBuffer; 63 jfieldID messageQueue; 64 jmethodID callback; 65 } gFrameMetricsObserverClassInfo; 66 67 static 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 79 void onRenderNodeRemoved(JNIEnv* env, RenderNode* node); 80 81 class ScopedRemovedRenderNodeObserver : public TreeObserver { 82 public: 83 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 95 private: 96 JNIEnv* mEnv; 97 std::set< sp<RenderNode> > mMaybeRemovedNodes; 98 }; 99 100 class OnFinishedEvent { 101 public: 102 OnFinishedEvent(BaseRenderNodeAnimator* animator, AnimationListener* listener) 103 : animator(animator), listener(listener) {} 104 sp<BaseRenderNodeAnimator> animator; 105 sp<AnimationListener> listener; 106 }; 107 108 class InvokeAnimationListeners : public MessageHandler { 109 public: 110 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 123 private: 124 std::vector<OnFinishedEvent> mOnFinishedEvents; 125 }; 126 127 class FinishAndInvokeListener : public MessageHandler { 128 public: 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 } 146 private: 147 sp<PropertyValuesAnimatorSet> mAnimator; 148 sp<AnimationListener> mListener; 149 uint32_t mRequestId; 150 }; 151 152 class RenderingException : public MessageHandler { 153 public: 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 168 private: 169 JavaVM* mVm; 170 std::string mMessage; 171 }; 172 173 class RootRenderNode : public RenderNode, ErrorHandler { 174 public: 175 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 365 private: 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 403 class AnimationContextBridge : public AnimationContext { 404 public: 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 443 private: 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 456 class ContextFactoryImpl : public IContextFactory { 457 public: 458 ContextFactoryImpl(RootRenderNode* rootNode) : mRootNode(rootNode) {} 459 460 virtual AnimationContext* createAnimationContext(renderthread::TimeLord& clock) { 461 return new AnimationContextBridge(clock, mRootNode); 462 } 463 464 private: 465 RootRenderNode* mRootNode; 466 }; 467 468 class ObserverProxy; 469 470 class NotifyHandler : public MessageHandler { 471 public: 472 NotifyHandler(JavaVM* vm, ObserverProxy* observer) : mVm(vm), mObserver(observer) {} 473 474 virtual void handleMessage(const Message& message); 475 476 private: 477 JavaVM* const mVm; 478 ObserverProxy* const mObserver; 479 }; 480 481 static 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 */ 494 class ObserverProxy : public FrameMetricsObserver { 495 public: 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 560 private: 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 jobject mJavaBufferGlobal; 576 577 sp<MessageQueue> mMessageQueue; 578 sp<NotifyHandler> mMessageHandler; 579 Message mMessage; 580 581 int mNextFree = 0; 582 int mNextInQueue = 0; 583 FrameMetricsNotification mRingBuffer[kRingSize]; 584 585 int mDroppedReports = 0; 586 }; 587 588 void NotifyHandler::handleMessage(const Message& message) { 589 JNIEnv* env = getenv(mVm); 590 591 jobject target = env->NewLocalRef(mObserver->getObserverReference()); 592 593 if (target != nullptr) { 594 jlongArray javaBuffer = get_metrics_buffer(env, target); 595 int dropCount = 0; 596 while (mObserver->getNextBuffer(env, javaBuffer, &dropCount)) { 597 env->CallVoidMethod(target, gFrameMetricsObserverClassInfo.callback, dropCount); 598 } 599 env->DeleteLocalRef(target); 600 } 601 602 mObserver->decStrong(nullptr); 603 } 604 605 static void android_view_ThreadedRenderer_setAtlas(JNIEnv* env, jobject clazz, 606 jlong proxyPtr, jobject graphicBuffer, jlongArray atlasMapArray) { 607 sp<GraphicBuffer> buffer = graphicBufferForJavaObject(env, graphicBuffer); 608 jsize len = env->GetArrayLength(atlasMapArray); 609 if (len <= 0) { 610 ALOGW("Failed to initialize atlas, invalid map length: %d", len); 611 return; 612 } 613 int64_t* map = new int64_t[len]; 614 env->GetLongArrayRegion(atlasMapArray, 0, len, map); 615 616 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 617 proxy->setTextureAtlas(buffer, map, len); 618 } 619 620 static void android_view_ThreadedRenderer_setProcessStatsBuffer(JNIEnv* env, jobject clazz, 621 jlong proxyPtr, jint fd) { 622 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 623 proxy->setProcessStatsBuffer(fd); 624 } 625 626 static jint android_view_ThreadedRenderer_getRenderThreadTid(JNIEnv* env, jobject clazz, 627 jlong proxyPtr) { 628 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 629 return proxy->getRenderThreadTid(); 630 } 631 632 static jlong android_view_ThreadedRenderer_createRootRenderNode(JNIEnv* env, jobject clazz) { 633 RootRenderNode* node = new RootRenderNode(env); 634 node->incStrong(0); 635 node->setName("RootRenderNode"); 636 return reinterpret_cast<jlong>(node); 637 } 638 639 static jlong android_view_ThreadedRenderer_createProxy(JNIEnv* env, jobject clazz, 640 jboolean translucent, jlong rootRenderNodePtr) { 641 RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootRenderNodePtr); 642 ContextFactoryImpl factory(rootRenderNode); 643 return (jlong) new RenderProxy(translucent, rootRenderNode, &factory); 644 } 645 646 static void android_view_ThreadedRenderer_deleteProxy(JNIEnv* env, jobject clazz, 647 jlong proxyPtr) { 648 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 649 delete proxy; 650 } 651 652 static jboolean android_view_ThreadedRenderer_loadSystemProperties(JNIEnv* env, jobject clazz, 653 jlong proxyPtr) { 654 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 655 return proxy->loadSystemProperties(); 656 } 657 658 static void android_view_ThreadedRenderer_setName(JNIEnv* env, jobject clazz, 659 jlong proxyPtr, jstring jname) { 660 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 661 const char* name = env->GetStringUTFChars(jname, NULL); 662 proxy->setName(name); 663 env->ReleaseStringUTFChars(jname, name); 664 } 665 666 static void android_view_ThreadedRenderer_initialize(JNIEnv* env, jobject clazz, 667 jlong proxyPtr, jobject jsurface) { 668 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 669 sp<Surface> surface = android_view_Surface_getSurface(env, jsurface); 670 proxy->initialize(surface); 671 } 672 673 static void android_view_ThreadedRenderer_updateSurface(JNIEnv* env, jobject clazz, 674 jlong proxyPtr, jobject jsurface) { 675 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 676 sp<Surface> surface; 677 if (jsurface) { 678 surface = android_view_Surface_getSurface(env, jsurface); 679 } 680 proxy->updateSurface(surface); 681 } 682 683 static jboolean android_view_ThreadedRenderer_pauseSurface(JNIEnv* env, jobject clazz, 684 jlong proxyPtr, jobject jsurface) { 685 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 686 sp<Surface> surface; 687 if (jsurface) { 688 surface = android_view_Surface_getSurface(env, jsurface); 689 } 690 return proxy->pauseSurface(surface); 691 } 692 693 static void android_view_ThreadedRenderer_setStopped(JNIEnv* env, jobject clazz, 694 jlong proxyPtr, jboolean stopped) { 695 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 696 proxy->setStopped(stopped); 697 } 698 699 static void android_view_ThreadedRenderer_setup(JNIEnv* env, jobject clazz, jlong proxyPtr, 700 jint width, jint height, jfloat lightRadius, jint ambientShadowAlpha, jint spotShadowAlpha) { 701 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 702 proxy->setup(width, height, lightRadius, ambientShadowAlpha, spotShadowAlpha); 703 } 704 705 static void android_view_ThreadedRenderer_setLightCenter(JNIEnv* env, jobject clazz, 706 jlong proxyPtr, jfloat lightX, jfloat lightY, jfloat lightZ) { 707 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 708 proxy->setLightCenter((Vector3){lightX, lightY, lightZ}); 709 } 710 711 static void android_view_ThreadedRenderer_setOpaque(JNIEnv* env, jobject clazz, 712 jlong proxyPtr, jboolean opaque) { 713 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 714 proxy->setOpaque(opaque); 715 } 716 717 static int android_view_ThreadedRenderer_syncAndDrawFrame(JNIEnv* env, jobject clazz, 718 jlong proxyPtr, jlongArray frameInfo, jint frameInfoSize) { 719 LOG_ALWAYS_FATAL_IF(frameInfoSize != UI_THREAD_FRAME_INFO_SIZE, 720 "Mismatched size expectations, given %d expected %d", 721 frameInfoSize, UI_THREAD_FRAME_INFO_SIZE); 722 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 723 ScopedRemovedRenderNodeObserver observer(env); 724 env->GetLongArrayRegion(frameInfo, 0, frameInfoSize, proxy->frameInfo()); 725 return proxy->syncAndDrawFrame(&observer); 726 } 727 728 static void android_view_ThreadedRenderer_destroy(JNIEnv* env, jobject clazz, 729 jlong proxyPtr, jlong rootNodePtr) { 730 ScopedRemovedRenderNodeObserver observer(env); 731 RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr); 732 rootRenderNode->destroy(); 733 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 734 proxy->destroy(&observer); 735 } 736 737 static void android_view_ThreadedRenderer_registerAnimatingRenderNode(JNIEnv* env, jobject clazz, 738 jlong rootNodePtr, jlong animatingNodePtr) { 739 RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr); 740 RenderNode* animatingNode = reinterpret_cast<RenderNode*>(animatingNodePtr); 741 rootRenderNode->attachAnimatingNode(animatingNode); 742 } 743 744 static void android_view_ThreadedRenderer_registerVectorDrawableAnimator(JNIEnv* env, jobject clazz, 745 jlong rootNodePtr, jlong animatorPtr) { 746 RootRenderNode* rootRenderNode = reinterpret_cast<RootRenderNode*>(rootNodePtr); 747 PropertyValuesAnimatorSet* animator = reinterpret_cast<PropertyValuesAnimatorSet*>(animatorPtr); 748 rootRenderNode->addVectorDrawableAnimator(animator); 749 } 750 751 static void android_view_ThreadedRenderer_invokeFunctor(JNIEnv* env, jobject clazz, 752 jlong functorPtr, jboolean waitForCompletion) { 753 Functor* functor = reinterpret_cast<Functor*>(functorPtr); 754 RenderProxy::invokeFunctor(functor, waitForCompletion); 755 } 756 757 static jlong android_view_ThreadedRenderer_createTextureLayer(JNIEnv* env, jobject clazz, 758 jlong proxyPtr) { 759 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 760 DeferredLayerUpdater* layer = proxy->createTextureLayer(); 761 return reinterpret_cast<jlong>(layer); 762 } 763 764 static void android_view_ThreadedRenderer_buildLayer(JNIEnv* env, jobject clazz, 765 jlong proxyPtr, jlong nodePtr) { 766 ScopedRemovedRenderNodeObserver observer(env); 767 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 768 RenderNode* node = reinterpret_cast<RenderNode*>(nodePtr); 769 proxy->buildLayer(node, &observer); 770 } 771 772 static jboolean android_view_ThreadedRenderer_copyLayerInto(JNIEnv* env, jobject clazz, 773 jlong proxyPtr, jlong layerPtr, jobject jbitmap) { 774 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 775 DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr); 776 SkBitmap bitmap; 777 GraphicsJNI::getSkBitmap(env, jbitmap, &bitmap); 778 return proxy->copyLayerInto(layer, bitmap); 779 } 780 781 static void android_view_ThreadedRenderer_pushLayerUpdate(JNIEnv* env, jobject clazz, 782 jlong proxyPtr, jlong layerPtr) { 783 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 784 DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr); 785 proxy->pushLayerUpdate(layer); 786 } 787 788 static void android_view_ThreadedRenderer_cancelLayerUpdate(JNIEnv* env, jobject clazz, 789 jlong proxyPtr, jlong layerPtr) { 790 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 791 DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr); 792 proxy->cancelLayerUpdate(layer); 793 } 794 795 static void android_view_ThreadedRenderer_detachSurfaceTexture(JNIEnv* env, jobject clazz, 796 jlong proxyPtr, jlong layerPtr) { 797 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 798 DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerPtr); 799 proxy->detachSurfaceTexture(layer); 800 } 801 802 static void android_view_ThreadedRenderer_destroyHardwareResources(JNIEnv* env, jobject clazz, 803 jlong proxyPtr) { 804 ScopedRemovedRenderNodeObserver observer(env); 805 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 806 proxy->destroyHardwareResources(&observer); 807 } 808 809 static void android_view_ThreadedRenderer_trimMemory(JNIEnv* env, jobject clazz, 810 jint level) { 811 RenderProxy::trimMemory(level); 812 } 813 814 static void android_view_ThreadedRenderer_overrideProperty(JNIEnv* env, jobject clazz, 815 jstring name, jstring value) { 816 const char* nameCharArray = env->GetStringUTFChars(name, NULL); 817 const char* valueCharArray = env->GetStringUTFChars(value, NULL); 818 RenderProxy::overrideProperty(nameCharArray, valueCharArray); 819 env->ReleaseStringUTFChars(name, nameCharArray); 820 env->ReleaseStringUTFChars(name, valueCharArray); 821 } 822 823 static void android_view_ThreadedRenderer_fence(JNIEnv* env, jobject clazz, 824 jlong proxyPtr) { 825 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 826 proxy->fence(); 827 } 828 829 static void android_view_ThreadedRenderer_stopDrawing(JNIEnv* env, jobject clazz, 830 jlong proxyPtr) { 831 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 832 proxy->stopDrawing(); 833 } 834 835 static void android_view_ThreadedRenderer_notifyFramePending(JNIEnv* env, jobject clazz, 836 jlong proxyPtr) { 837 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 838 proxy->notifyFramePending(); 839 } 840 841 static void android_view_ThreadedRenderer_serializeDisplayListTree(JNIEnv* env, jobject clazz, 842 jlong proxyPtr) { 843 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 844 proxy->serializeDisplayListTree(); 845 } 846 847 static void android_view_ThreadedRenderer_dumpProfileInfo(JNIEnv* env, jobject clazz, 848 jlong proxyPtr, jobject javaFileDescriptor, jint dumpFlags) { 849 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 850 int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor); 851 proxy->dumpProfileInfo(fd, dumpFlags); 852 } 853 854 static void android_view_ThreadedRenderer_dumpProfileData(JNIEnv* env, jobject clazz, 855 jbyteArray jdata, jobject javaFileDescriptor) { 856 int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor); 857 ScopedByteArrayRO buffer(env, jdata); 858 if (buffer.get()) { 859 JankTracker::dumpBuffer(buffer.get(), buffer.size(), fd); 860 } 861 } 862 863 static void android_view_ThreadedRenderer_addRenderNode(JNIEnv* env, jobject clazz, 864 jlong proxyPtr, jlong renderNodePtr, jboolean placeFront) { 865 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 866 RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr); 867 proxy->addRenderNode(renderNode, placeFront); 868 } 869 870 static void android_view_ThreadedRenderer_removeRenderNode(JNIEnv* env, jobject clazz, 871 jlong proxyPtr, jlong renderNodePtr) { 872 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 873 RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr); 874 proxy->removeRenderNode(renderNode); 875 } 876 877 static void android_view_ThreadedRendererd_drawRenderNode(JNIEnv* env, jobject clazz, 878 jlong proxyPtr, jlong renderNodePtr) { 879 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 880 RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr); 881 proxy->drawRenderNode(renderNode); 882 } 883 884 static void android_view_ThreadedRenderer_setContentDrawBounds(JNIEnv* env, 885 jobject clazz, jlong proxyPtr, jint left, jint top, jint right, jint bottom) { 886 RenderProxy* proxy = reinterpret_cast<RenderProxy*>(proxyPtr); 887 proxy->setContentDrawBounds(left, top, right, bottom); 888 } 889 890 static jint android_view_ThreadedRenderer_copySurfaceInto(JNIEnv* env, 891 jobject clazz, jobject jsurface, jobject jbitmap) { 892 SkBitmap bitmap; 893 GraphicsJNI::getSkBitmap(env, jbitmap, &bitmap); 894 sp<Surface> surface = android_view_Surface_getSurface(env, jsurface); 895 return RenderProxy::copySurfaceInto(surface, &bitmap); 896 } 897 898 // ---------------------------------------------------------------------------- 899 // FrameMetricsObserver 900 // ---------------------------------------------------------------------------- 901 902 static jlong android_view_ThreadedRenderer_addFrameMetricsObserver(JNIEnv* env, 903 jclass clazz, jlong proxyPtr, jobject fso) { 904 JavaVM* vm = nullptr; 905 if (env->GetJavaVM(&vm) != JNI_OK) { 906 LOG_ALWAYS_FATAL("Unable to get Java VM"); 907 return 0; 908 } 909 910 renderthread::RenderProxy* renderProxy = 911 reinterpret_cast<renderthread::RenderProxy*>(proxyPtr); 912 913 FrameMetricsObserver* observer = new ObserverProxy(vm, fso); 914 renderProxy->addFrameMetricsObserver(observer); 915 return reinterpret_cast<jlong>(observer); 916 } 917 918 static void android_view_ThreadedRenderer_removeFrameMetricsObserver(JNIEnv* env, jclass clazz, 919 jlong proxyPtr, jlong observerPtr) { 920 FrameMetricsObserver* observer = reinterpret_cast<FrameMetricsObserver*>(observerPtr); 921 renderthread::RenderProxy* renderProxy = 922 reinterpret_cast<renderthread::RenderProxy*>(proxyPtr); 923 924 renderProxy->removeFrameMetricsObserver(observer); 925 } 926 927 // ---------------------------------------------------------------------------- 928 // Shaders 929 // ---------------------------------------------------------------------------- 930 931 static void android_view_ThreadedRenderer_setupShadersDiskCache(JNIEnv* env, jobject clazz, 932 jstring diskCachePath) { 933 const char* cacheArray = env->GetStringUTFChars(diskCachePath, NULL); 934 egl_cache_t::get()->setCacheFilename(cacheArray); 935 env->ReleaseStringUTFChars(diskCachePath, cacheArray); 936 } 937 938 // ---------------------------------------------------------------------------- 939 // JNI Glue 940 // ---------------------------------------------------------------------------- 941 942 const char* const kClassPathName = "android/view/ThreadedRenderer"; 943 944 static const JNINativeMethod gMethods[] = { 945 { "nSetAtlas", "(JLandroid/view/GraphicBuffer;[J)V", (void*) android_view_ThreadedRenderer_setAtlas }, 946 { "nSetProcessStatsBuffer", "(JI)V", (void*) android_view_ThreadedRenderer_setProcessStatsBuffer }, 947 { "nGetRenderThreadTid", "(J)I", (void*) android_view_ThreadedRenderer_getRenderThreadTid }, 948 { "nCreateRootRenderNode", "()J", (void*) android_view_ThreadedRenderer_createRootRenderNode }, 949 { "nCreateProxy", "(ZJ)J", (void*) android_view_ThreadedRenderer_createProxy }, 950 { "nDeleteProxy", "(J)V", (void*) android_view_ThreadedRenderer_deleteProxy }, 951 { "nLoadSystemProperties", "(J)Z", (void*) android_view_ThreadedRenderer_loadSystemProperties }, 952 { "nSetName", "(JLjava/lang/String;)V", (void*) android_view_ThreadedRenderer_setName }, 953 { "nInitialize", "(JLandroid/view/Surface;)V", (void*) android_view_ThreadedRenderer_initialize }, 954 { "nUpdateSurface", "(JLandroid/view/Surface;)V", (void*) android_view_ThreadedRenderer_updateSurface }, 955 { "nPauseSurface", "(JLandroid/view/Surface;)Z", (void*) android_view_ThreadedRenderer_pauseSurface }, 956 { "nSetStopped", "(JZ)V", (void*) android_view_ThreadedRenderer_setStopped }, 957 { "nSetup", "(JIIFII)V", (void*) android_view_ThreadedRenderer_setup }, 958 { "nSetLightCenter", "(JFFF)V", (void*) android_view_ThreadedRenderer_setLightCenter }, 959 { "nSetOpaque", "(JZ)V", (void*) android_view_ThreadedRenderer_setOpaque }, 960 { "nSyncAndDrawFrame", "(J[JI)I", (void*) android_view_ThreadedRenderer_syncAndDrawFrame }, 961 { "nDestroy", "(JJ)V", (void*) android_view_ThreadedRenderer_destroy }, 962 { "nRegisterAnimatingRenderNode", "(JJ)V", (void*) android_view_ThreadedRenderer_registerAnimatingRenderNode }, 963 { "nRegisterVectorDrawableAnimator", "(JJ)V", (void*) android_view_ThreadedRenderer_registerVectorDrawableAnimator }, 964 { "nInvokeFunctor", "(JZ)V", (void*) android_view_ThreadedRenderer_invokeFunctor }, 965 { "nCreateTextureLayer", "(J)J", (void*) android_view_ThreadedRenderer_createTextureLayer }, 966 { "nBuildLayer", "(JJ)V", (void*) android_view_ThreadedRenderer_buildLayer }, 967 { "nCopyLayerInto", "(JJLandroid/graphics/Bitmap;)Z", (void*) android_view_ThreadedRenderer_copyLayerInto }, 968 { "nPushLayerUpdate", "(JJ)V", (void*) android_view_ThreadedRenderer_pushLayerUpdate }, 969 { "nCancelLayerUpdate", "(JJ)V", (void*) android_view_ThreadedRenderer_cancelLayerUpdate }, 970 { "nDetachSurfaceTexture", "(JJ)V", (void*) android_view_ThreadedRenderer_detachSurfaceTexture }, 971 { "nDestroyHardwareResources", "(J)V", (void*) android_view_ThreadedRenderer_destroyHardwareResources }, 972 { "nTrimMemory", "(I)V", (void*) android_view_ThreadedRenderer_trimMemory }, 973 { "nOverrideProperty", "(Ljava/lang/String;Ljava/lang/String;)V", (void*) android_view_ThreadedRenderer_overrideProperty }, 974 { "nFence", "(J)V", (void*) android_view_ThreadedRenderer_fence }, 975 { "nStopDrawing", "(J)V", (void*) android_view_ThreadedRenderer_stopDrawing }, 976 { "nNotifyFramePending", "(J)V", (void*) android_view_ThreadedRenderer_notifyFramePending }, 977 { "nSerializeDisplayListTree", "(J)V", (void*) android_view_ThreadedRenderer_serializeDisplayListTree }, 978 { "nDumpProfileInfo", "(JLjava/io/FileDescriptor;I)V", (void*) android_view_ThreadedRenderer_dumpProfileInfo }, 979 { "nDumpProfileData", "([BLjava/io/FileDescriptor;)V", (void*) android_view_ThreadedRenderer_dumpProfileData }, 980 { "setupShadersDiskCache", "(Ljava/lang/String;)V", 981 (void*) android_view_ThreadedRenderer_setupShadersDiskCache }, 982 { "nAddRenderNode", "(JJZ)V", (void*) android_view_ThreadedRenderer_addRenderNode}, 983 { "nRemoveRenderNode", "(JJ)V", (void*) android_view_ThreadedRenderer_removeRenderNode}, 984 { "nDrawRenderNode", "(JJ)V", (void*) android_view_ThreadedRendererd_drawRenderNode}, 985 { "nSetContentDrawBounds", "(JIIII)V", (void*)android_view_ThreadedRenderer_setContentDrawBounds}, 986 { "nAddFrameMetricsObserver", 987 "(JLandroid/view/FrameMetricsObserver;)J", 988 (void*)android_view_ThreadedRenderer_addFrameMetricsObserver }, 989 { "nRemoveFrameMetricsObserver", 990 "(JJ)V", 991 (void*)android_view_ThreadedRenderer_removeFrameMetricsObserver }, 992 { "nCopySurfaceInto", "(Landroid/view/Surface;Landroid/graphics/Bitmap;)I", 993 (void*)android_view_ThreadedRenderer_copySurfaceInto }, 994 }; 995 996 int register_android_view_ThreadedRenderer(JNIEnv* env) { 997 jclass observerClass = FindClassOrDie(env, "android/view/FrameMetricsObserver"); 998 gFrameMetricsObserverClassInfo.frameMetrics = GetFieldIDOrDie( 999 env, observerClass, "mFrameMetrics", "Landroid/view/FrameMetrics;"); 1000 gFrameMetricsObserverClassInfo.messageQueue = GetFieldIDOrDie( 1001 env, observerClass, "mMessageQueue", "Landroid/os/MessageQueue;"); 1002 gFrameMetricsObserverClassInfo.callback = GetMethodIDOrDie( 1003 env, observerClass, "notifyDataAvailable", "(I)V"); 1004 1005 jclass metricsClass = FindClassOrDie(env, "android/view/FrameMetrics"); 1006 gFrameMetricsObserverClassInfo.timingDataBuffer = GetFieldIDOrDie( 1007 env, metricsClass, "mTimingData", "[J"); 1008 1009 return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); 1010 } 1011 1012 }; // namespace android 1013