1 /*
2  * Copyright (C) 2015 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 "Choreographer"
18 //#define LOG_NDEBUG 0
19 
20 #include <android-base/thread_annotations.h>
21 #include <gui/DisplayEventDispatcher.h>
22 #include <gui/ISurfaceComposer.h>
23 #include <jni.h>
24 #include <private/android/choreographer.h>
25 #include <utils/Looper.h>
26 #include <utils/Timers.h>
27 
28 #include <cinttypes>
29 #include <mutex>
30 #include <optional>
31 #include <queue>
32 #include <thread>
33 
34 namespace {
35 struct {
36     // Global JVM that is provided by zygote
37     JavaVM* jvm = nullptr;
38     struct {
39         jclass clazz;
40         jmethodID getInstance;
41         jmethodID registerNativeChoreographerForRefreshRateCallbacks;
42         jmethodID unregisterNativeChoreographerForRefreshRateCallbacks;
43     } displayManagerGlobal;
44 } gJni;
45 
46 // Gets the JNIEnv* for this thread, and performs one-off initialization if we
47 // have never retrieved a JNIEnv* pointer before.
getJniEnv()48 JNIEnv* getJniEnv() {
49     if (gJni.jvm == nullptr) {
50         ALOGW("AChoreographer: No JVM provided!");
51         return nullptr;
52     }
53 
54     JNIEnv* env = nullptr;
55     if (gJni.jvm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) {
56         ALOGD("Attaching thread to JVM for AChoreographer");
57         JavaVMAttachArgs args = {JNI_VERSION_1_4, "AChoreographer_env", NULL};
58         jint attachResult = gJni.jvm->AttachCurrentThreadAsDaemon(&env, (void*)&args);
59         if (attachResult != JNI_OK) {
60             ALOGE("Unable to attach thread. Error: %d", attachResult);
61             return nullptr;
62         }
63     }
64     if (env == nullptr) {
65         ALOGW("AChoreographer: No JNI env available!");
66     }
67     return env;
68 }
69 
toString(bool value)70 inline const char* toString(bool value) {
71     return value ? "true" : "false";
72 }
73 } // namespace
74 
75 namespace android {
76 
77 struct FrameCallback {
78     AChoreographer_frameCallback callback;
79     AChoreographer_frameCallback64 callback64;
80     void* data;
81     nsecs_t dueTime;
82 
operator <android::FrameCallback83     inline bool operator<(const FrameCallback& rhs) const {
84         // Note that this is intentionally flipped because we want callbacks due sooner to be at
85         // the head of the queue
86         return dueTime > rhs.dueTime;
87     }
88 };
89 
90 struct RefreshRateCallback {
91     AChoreographer_refreshRateCallback callback;
92     void* data;
93     bool firstCallbackFired = false;
94 };
95 
96 class Choreographer;
97 
98 struct {
99     std::mutex lock;
100     std::vector<Choreographer*> ptrs GUARDED_BY(lock);
101     bool registeredToDisplayManager GUARDED_BY(lock) = false;
102 
103     std::atomic<nsecs_t> mLastKnownVsync = -1;
104 } gChoreographers;
105 
106 class Choreographer : public DisplayEventDispatcher, public MessageHandler {
107 public:
108     explicit Choreographer(const sp<Looper>& looper) EXCLUDES(gChoreographers.lock);
109     void postFrameCallbackDelayed(AChoreographer_frameCallback cb,
110                                   AChoreographer_frameCallback64 cb64, void* data, nsecs_t delay);
111     void registerRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data)
112             EXCLUDES(gChoreographers.lock);
113     void unregisterRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data);
114     // Drains the queue of pending vsync periods and dispatches refresh rate
115     // updates to callbacks.
116     // The assumption is that this method is only called on a single
117     // processing thread, either by looper or by AChoreographer_handleEvents
118     void handleRefreshRateUpdates();
119     void scheduleLatestConfigRequest();
120 
121     enum {
122         MSG_SCHEDULE_CALLBACKS = 0,
123         MSG_SCHEDULE_VSYNC = 1,
124         MSG_HANDLE_REFRESH_RATE_UPDATES = 2,
125     };
126     virtual void handleMessage(const Message& message) override;
127 
128     static Choreographer* getForThread();
129     virtual ~Choreographer() override EXCLUDES(gChoreographers.lock);
130     int64_t getVsyncId() const;
131     int64_t getFrameDeadline() const;
132     int64_t getFrameInterval() const;
133 
134 private:
135     Choreographer(const Choreographer&) = delete;
136 
137     void dispatchVsync(nsecs_t timestamp, PhysicalDisplayId displayId, uint32_t count,
138                        VsyncEventData vsyncEventData) override;
139     void dispatchHotplug(nsecs_t timestamp, PhysicalDisplayId displayId, bool connected) override;
140     void dispatchModeChanged(nsecs_t timestamp, PhysicalDisplayId displayId, int32_t modeId,
141                              nsecs_t vsyncPeriod) override;
142     void dispatchNullEvent(nsecs_t, PhysicalDisplayId) override;
143     void dispatchFrameRateOverrides(nsecs_t timestamp, PhysicalDisplayId displayId,
144                                     std::vector<FrameRateOverride> overrides) override;
145 
146     void scheduleCallbacks();
147 
148     std::mutex mLock;
149     // Protected by mLock
150     std::priority_queue<FrameCallback> mFrameCallbacks;
151     std::vector<RefreshRateCallback> mRefreshRateCallbacks;
152 
153     nsecs_t mLatestVsyncPeriod = -1;
154     VsyncEventData mLastVsyncEventData;
155 
156     const sp<Looper> mLooper;
157     const std::thread::id mThreadId;
158 };
159 
160 static thread_local Choreographer* gChoreographer;
getForThread()161 Choreographer* Choreographer::getForThread() {
162     if (gChoreographer == nullptr) {
163         sp<Looper> looper = Looper::getForThread();
164         if (!looper.get()) {
165             ALOGW("No looper prepared for thread");
166             return nullptr;
167         }
168         gChoreographer = new Choreographer(looper);
169         status_t result = gChoreographer->initialize();
170         if (result != OK) {
171             ALOGW("Failed to initialize");
172             return nullptr;
173         }
174     }
175     return gChoreographer;
176 }
177 
Choreographer(const sp<Looper> & looper)178 Choreographer::Choreographer(const sp<Looper>& looper)
179       : DisplayEventDispatcher(looper, ISurfaceComposer::VsyncSource::eVsyncSourceApp),
180         mLooper(looper),
181         mThreadId(std::this_thread::get_id()) {
182     std::lock_guard<std::mutex> _l(gChoreographers.lock);
183     gChoreographers.ptrs.push_back(this);
184 }
185 
~Choreographer()186 Choreographer::~Choreographer() {
187     std::lock_guard<std::mutex> _l(gChoreographers.lock);
188     gChoreographers.ptrs.erase(std::remove_if(gChoreographers.ptrs.begin(),
189                                               gChoreographers.ptrs.end(),
190                                               [=](Choreographer* c) { return c == this; }),
191                                gChoreographers.ptrs.end());
192     // Only poke DisplayManagerGlobal to unregister if we previously registered
193     // callbacks.
194     if (gChoreographers.ptrs.empty() && gChoreographers.registeredToDisplayManager) {
195         JNIEnv* env = getJniEnv();
196         if (env == nullptr) {
197             ALOGW("JNI environment is unavailable, skipping choreographer cleanup");
198             return;
199         }
200         jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
201                                                   gJni.displayManagerGlobal.getInstance);
202         if (dmg == nullptr) {
203             ALOGW("DMS is not initialized yet, skipping choreographer cleanup");
204         } else {
205             env->CallVoidMethod(dmg,
206                                 gJni.displayManagerGlobal
207                                         .unregisterNativeChoreographerForRefreshRateCallbacks);
208             env->DeleteLocalRef(dmg);
209         }
210     }
211 }
212 
postFrameCallbackDelayed(AChoreographer_frameCallback cb,AChoreographer_frameCallback64 cb64,void * data,nsecs_t delay)213 void Choreographer::postFrameCallbackDelayed(
214         AChoreographer_frameCallback cb, AChoreographer_frameCallback64 cb64, void* data, nsecs_t delay) {
215     nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
216     FrameCallback callback{cb, cb64, data, now + delay};
217     {
218         std::lock_guard<std::mutex> _l{mLock};
219         mFrameCallbacks.push(callback);
220     }
221     if (callback.dueTime <= now) {
222         if (std::this_thread::get_id() != mThreadId) {
223             if (mLooper != nullptr) {
224                 Message m{MSG_SCHEDULE_VSYNC};
225                 mLooper->sendMessage(this, m);
226             } else {
227                 scheduleVsync();
228             }
229         } else {
230             scheduleVsync();
231         }
232     } else {
233         if (mLooper != nullptr) {
234             Message m{MSG_SCHEDULE_CALLBACKS};
235             mLooper->sendMessageDelayed(delay, this, m);
236         } else {
237             scheduleCallbacks();
238         }
239     }
240 }
241 
registerRefreshRateCallback(AChoreographer_refreshRateCallback cb,void * data)242 void Choreographer::registerRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data) {
243     std::lock_guard<std::mutex> _l{mLock};
244     for (const auto& callback : mRefreshRateCallbacks) {
245         // Don't re-add callbacks.
246         if (cb == callback.callback && data == callback.data) {
247             return;
248         }
249     }
250     mRefreshRateCallbacks.emplace_back(
251             RefreshRateCallback{.callback = cb, .data = data, .firstCallbackFired = false});
252     bool needsRegistration = false;
253     {
254         std::lock_guard<std::mutex> _l2(gChoreographers.lock);
255         needsRegistration = !gChoreographers.registeredToDisplayManager;
256     }
257     if (needsRegistration) {
258         JNIEnv* env = getJniEnv();
259         if (env == nullptr) {
260             ALOGW("JNI environment is unavailable, skipping registration");
261             return;
262         }
263         jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
264                                                   gJni.displayManagerGlobal.getInstance);
265         if (dmg == nullptr) {
266             ALOGW("DMS is not initialized yet: skipping registration");
267             return;
268         } else {
269             env->CallVoidMethod(dmg,
270                                 gJni.displayManagerGlobal
271                                         .registerNativeChoreographerForRefreshRateCallbacks,
272                                 reinterpret_cast<int64_t>(this));
273             env->DeleteLocalRef(dmg);
274             {
275                 std::lock_guard<std::mutex> _l2(gChoreographers.lock);
276                 gChoreographers.registeredToDisplayManager = true;
277             }
278         }
279     } else {
280         scheduleLatestConfigRequest();
281     }
282 }
283 
unregisterRefreshRateCallback(AChoreographer_refreshRateCallback cb,void * data)284 void Choreographer::unregisterRefreshRateCallback(AChoreographer_refreshRateCallback cb,
285                                                   void* data) {
286     std::lock_guard<std::mutex> _l{mLock};
287     mRefreshRateCallbacks.erase(std::remove_if(mRefreshRateCallbacks.begin(),
288                                                mRefreshRateCallbacks.end(),
289                                                [&](const RefreshRateCallback& callback) {
290                                                    return cb == callback.callback &&
291                                                            data == callback.data;
292                                                }),
293                                 mRefreshRateCallbacks.end());
294 }
295 
scheduleLatestConfigRequest()296 void Choreographer::scheduleLatestConfigRequest() {
297     if (mLooper != nullptr) {
298         Message m{MSG_HANDLE_REFRESH_RATE_UPDATES};
299         mLooper->sendMessage(this, m);
300     } else {
301         // If the looper thread is detached from Choreographer, then refresh rate
302         // changes will be handled in AChoreographer_handlePendingEvents, so we
303         // need to wake up the looper thread by writing to the write-end of the
304         // socket the looper is listening on.
305         // Fortunately, these events are small so sending packets across the
306         // socket should be atomic across processes.
307         DisplayEventReceiver::Event event;
308         event.header = DisplayEventReceiver::Event::Header{DisplayEventReceiver::DISPLAY_EVENT_NULL,
309                                                            PhysicalDisplayId(0), systemTime()};
310         injectEvent(event);
311     }
312 }
313 
scheduleCallbacks()314 void Choreographer::scheduleCallbacks() {
315     const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
316     nsecs_t dueTime;
317     {
318         std::lock_guard<std::mutex> _l{mLock};
319         // If there are no pending callbacks then don't schedule a vsync
320         if (mFrameCallbacks.empty()) {
321             return;
322         }
323         dueTime = mFrameCallbacks.top().dueTime;
324     }
325 
326     if (dueTime <= now) {
327         ALOGV("choreographer %p ~ scheduling vsync", this);
328         scheduleVsync();
329         return;
330     }
331 }
332 
handleRefreshRateUpdates()333 void Choreographer::handleRefreshRateUpdates() {
334     std::vector<RefreshRateCallback> callbacks{};
335     const nsecs_t pendingPeriod = gChoreographers.mLastKnownVsync.load();
336     const nsecs_t lastPeriod = mLatestVsyncPeriod;
337     if (pendingPeriod > 0) {
338         mLatestVsyncPeriod = pendingPeriod;
339     }
340     {
341         std::lock_guard<std::mutex> _l{mLock};
342         for (auto& cb : mRefreshRateCallbacks) {
343             callbacks.push_back(cb);
344             cb.firstCallbackFired = true;
345         }
346     }
347 
348     for (auto& cb : callbacks) {
349         if (!cb.firstCallbackFired || (pendingPeriod > 0 && pendingPeriod != lastPeriod)) {
350             cb.callback(pendingPeriod, cb.data);
351         }
352     }
353 }
354 
355 // TODO(b/74619554): The PhysicalDisplayId is ignored because SF only emits VSYNC events for the
356 // internal display and DisplayEventReceiver::requestNextVsync only allows requesting VSYNC for
357 // the internal display implicitly.
dispatchVsync(nsecs_t timestamp,PhysicalDisplayId,uint32_t,VsyncEventData vsyncEventData)358 void Choreographer::dispatchVsync(nsecs_t timestamp, PhysicalDisplayId, uint32_t,
359                                   VsyncEventData vsyncEventData) {
360     std::vector<FrameCallback> callbacks{};
361     {
362         std::lock_guard<std::mutex> _l{mLock};
363         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
364         while (!mFrameCallbacks.empty() && mFrameCallbacks.top().dueTime < now) {
365             callbacks.push_back(mFrameCallbacks.top());
366             mFrameCallbacks.pop();
367         }
368     }
369     mLastVsyncEventData = vsyncEventData;
370     for (const auto& cb : callbacks) {
371         if (cb.callback64 != nullptr) {
372             cb.callback64(timestamp, cb.data);
373         } else if (cb.callback != nullptr) {
374             cb.callback(timestamp, cb.data);
375         }
376     }
377 }
378 
dispatchHotplug(nsecs_t,PhysicalDisplayId displayId,bool connected)379 void Choreographer::dispatchHotplug(nsecs_t, PhysicalDisplayId displayId, bool connected) {
380     ALOGV("choreographer %p ~ received hotplug event (displayId=%s, connected=%s), ignoring.",
381             this, to_string(displayId).c_str(), toString(connected));
382 }
383 
dispatchModeChanged(nsecs_t,PhysicalDisplayId,int32_t,nsecs_t)384 void Choreographer::dispatchModeChanged(nsecs_t, PhysicalDisplayId, int32_t, nsecs_t) {
385     LOG_ALWAYS_FATAL("dispatchModeChanged was called but was never registered");
386 }
387 
dispatchFrameRateOverrides(nsecs_t,PhysicalDisplayId,std::vector<FrameRateOverride>)388 void Choreographer::dispatchFrameRateOverrides(nsecs_t, PhysicalDisplayId,
389                                                std::vector<FrameRateOverride>) {
390     LOG_ALWAYS_FATAL("dispatchFrameRateOverrides was called but was never registered");
391 }
392 
dispatchNullEvent(nsecs_t,PhysicalDisplayId)393 void Choreographer::dispatchNullEvent(nsecs_t, PhysicalDisplayId) {
394     ALOGV("choreographer %p ~ received null event.", this);
395     handleRefreshRateUpdates();
396 }
397 
handleMessage(const Message & message)398 void Choreographer::handleMessage(const Message& message) {
399     switch (message.what) {
400     case MSG_SCHEDULE_CALLBACKS:
401         scheduleCallbacks();
402         break;
403     case MSG_SCHEDULE_VSYNC:
404         scheduleVsync();
405         break;
406     case MSG_HANDLE_REFRESH_RATE_UPDATES:
407         handleRefreshRateUpdates();
408         break;
409     }
410 }
411 
getVsyncId() const412 int64_t Choreographer::getVsyncId() const {
413     return mLastVsyncEventData.id;
414 }
415 
getFrameDeadline() const416 int64_t Choreographer::getFrameDeadline() const {
417     return mLastVsyncEventData.deadlineTimestamp;
418 }
419 
getFrameInterval() const420 int64_t Choreographer::getFrameInterval() const {
421     return mLastVsyncEventData.frameInterval;
422 }
423 
424 } // namespace android
425 using namespace android;
426 
AChoreographer_to_Choreographer(AChoreographer * choreographer)427 static inline Choreographer* AChoreographer_to_Choreographer(AChoreographer* choreographer) {
428     return reinterpret_cast<Choreographer*>(choreographer);
429 }
430 
AChoreographer_to_Choreographer(const AChoreographer * choreographer)431 static inline const Choreographer* AChoreographer_to_Choreographer(
432         const AChoreographer* choreographer) {
433     return reinterpret_cast<const Choreographer*>(choreographer);
434 }
435 
436 // Glue for private C api
437 namespace android {
AChoreographer_signalRefreshRateCallbacks(nsecs_t vsyncPeriod)438 void AChoreographer_signalRefreshRateCallbacks(nsecs_t vsyncPeriod) EXCLUDES(gChoreographers.lock) {
439     std::lock_guard<std::mutex> _l(gChoreographers.lock);
440     gChoreographers.mLastKnownVsync.store(vsyncPeriod);
441     for (auto c : gChoreographers.ptrs) {
442         c->scheduleLatestConfigRequest();
443     }
444 }
445 
AChoreographer_initJVM(JNIEnv * env)446 void AChoreographer_initJVM(JNIEnv* env) {
447     env->GetJavaVM(&gJni.jvm);
448     // Now we need to find the java classes.
449     jclass dmgClass = env->FindClass("android/hardware/display/DisplayManagerGlobal");
450     gJni.displayManagerGlobal.clazz = static_cast<jclass>(env->NewGlobalRef(dmgClass));
451     gJni.displayManagerGlobal.getInstance =
452             env->GetStaticMethodID(dmgClass, "getInstance",
453                                    "()Landroid/hardware/display/DisplayManagerGlobal;");
454     gJni.displayManagerGlobal.registerNativeChoreographerForRefreshRateCallbacks =
455             env->GetMethodID(dmgClass, "registerNativeChoreographerForRefreshRateCallbacks", "()V");
456     gJni.displayManagerGlobal.unregisterNativeChoreographerForRefreshRateCallbacks =
457             env->GetMethodID(dmgClass, "unregisterNativeChoreographerForRefreshRateCallbacks",
458                              "()V");
459 }
460 
AChoreographer_routeGetInstance()461 AChoreographer* AChoreographer_routeGetInstance() {
462     return AChoreographer_getInstance();
463 }
AChoreographer_routePostFrameCallback(AChoreographer * choreographer,AChoreographer_frameCallback callback,void * data)464 void AChoreographer_routePostFrameCallback(AChoreographer* choreographer,
465                                            AChoreographer_frameCallback callback, void* data) {
466 #pragma clang diagnostic push
467 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
468     return AChoreographer_postFrameCallback(choreographer, callback, data);
469 #pragma clang diagnostic pop
470 }
AChoreographer_routePostFrameCallbackDelayed(AChoreographer * choreographer,AChoreographer_frameCallback callback,void * data,long delayMillis)471 void AChoreographer_routePostFrameCallbackDelayed(AChoreographer* choreographer,
472                                                   AChoreographer_frameCallback callback, void* data,
473                                                   long delayMillis) {
474 #pragma clang diagnostic push
475 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
476     return AChoreographer_postFrameCallbackDelayed(choreographer, callback, data, delayMillis);
477 #pragma clang diagnostic pop
478 }
AChoreographer_routePostFrameCallback64(AChoreographer * choreographer,AChoreographer_frameCallback64 callback,void * data)479 void AChoreographer_routePostFrameCallback64(AChoreographer* choreographer,
480                                              AChoreographer_frameCallback64 callback, void* data) {
481     return AChoreographer_postFrameCallback64(choreographer, callback, data);
482 }
AChoreographer_routePostFrameCallbackDelayed64(AChoreographer * choreographer,AChoreographer_frameCallback64 callback,void * data,uint32_t delayMillis)483 void AChoreographer_routePostFrameCallbackDelayed64(AChoreographer* choreographer,
484                                                     AChoreographer_frameCallback64 callback,
485                                                     void* data, uint32_t delayMillis) {
486     return AChoreographer_postFrameCallbackDelayed64(choreographer, callback, data, delayMillis);
487 }
AChoreographer_routeRegisterRefreshRateCallback(AChoreographer * choreographer,AChoreographer_refreshRateCallback callback,void * data)488 void AChoreographer_routeRegisterRefreshRateCallback(AChoreographer* choreographer,
489                                                      AChoreographer_refreshRateCallback callback,
490                                                      void* data) {
491     return AChoreographer_registerRefreshRateCallback(choreographer, callback, data);
492 }
AChoreographer_routeUnregisterRefreshRateCallback(AChoreographer * choreographer,AChoreographer_refreshRateCallback callback,void * data)493 void AChoreographer_routeUnregisterRefreshRateCallback(AChoreographer* choreographer,
494                                                        AChoreographer_refreshRateCallback callback,
495                                                        void* data) {
496     return AChoreographer_unregisterRefreshRateCallback(choreographer, callback, data);
497 }
498 
AChoreographer_getVsyncId(const AChoreographer * choreographer)499 int64_t AChoreographer_getVsyncId(const AChoreographer* choreographer) {
500     return AChoreographer_to_Choreographer(choreographer)->getVsyncId();
501 }
502 
AChoreographer_getFrameDeadline(const AChoreographer * choreographer)503 int64_t AChoreographer_getFrameDeadline(const AChoreographer* choreographer) {
504     return AChoreographer_to_Choreographer(choreographer)->getFrameDeadline();
505 }
506 
AChoreographer_getFrameInterval(const AChoreographer * choreographer)507 int64_t AChoreographer_getFrameInterval(const AChoreographer* choreographer) {
508     return AChoreographer_to_Choreographer(choreographer)->getFrameInterval();
509 }
510 
511 } // namespace android
512 
513 /* Glue for the NDK interface */
514 
Choreographer_to_AChoreographer(Choreographer * choreographer)515 static inline AChoreographer* Choreographer_to_AChoreographer(Choreographer* choreographer) {
516     return reinterpret_cast<AChoreographer*>(choreographer);
517 }
518 
AChoreographer_getInstance()519 AChoreographer* AChoreographer_getInstance() {
520     return Choreographer_to_AChoreographer(Choreographer::getForThread());
521 }
522 
AChoreographer_postFrameCallback(AChoreographer * choreographer,AChoreographer_frameCallback callback,void * data)523 void AChoreographer_postFrameCallback(AChoreographer* choreographer,
524         AChoreographer_frameCallback callback, void* data) {
525     AChoreographer_to_Choreographer(choreographer)->postFrameCallbackDelayed(
526             callback, nullptr, data, 0);
527 }
AChoreographer_postFrameCallbackDelayed(AChoreographer * choreographer,AChoreographer_frameCallback callback,void * data,long delayMillis)528 void AChoreographer_postFrameCallbackDelayed(AChoreographer* choreographer,
529         AChoreographer_frameCallback callback, void* data, long delayMillis) {
530     AChoreographer_to_Choreographer(choreographer)->postFrameCallbackDelayed(
531             callback, nullptr, data, ms2ns(delayMillis));
532 }
AChoreographer_postFrameCallback64(AChoreographer * choreographer,AChoreographer_frameCallback64 callback,void * data)533 void AChoreographer_postFrameCallback64(AChoreographer* choreographer,
534         AChoreographer_frameCallback64 callback, void* data) {
535     AChoreographer_to_Choreographer(choreographer)->postFrameCallbackDelayed(
536             nullptr, callback, data, 0);
537 }
AChoreographer_postFrameCallbackDelayed64(AChoreographer * choreographer,AChoreographer_frameCallback64 callback,void * data,uint32_t delayMillis)538 void AChoreographer_postFrameCallbackDelayed64(AChoreographer* choreographer,
539         AChoreographer_frameCallback64 callback, void* data, uint32_t delayMillis) {
540     AChoreographer_to_Choreographer(choreographer)->postFrameCallbackDelayed(
541             nullptr, callback, data, ms2ns(delayMillis));
542 }
AChoreographer_registerRefreshRateCallback(AChoreographer * choreographer,AChoreographer_refreshRateCallback callback,void * data)543 void AChoreographer_registerRefreshRateCallback(AChoreographer* choreographer,
544                                                 AChoreographer_refreshRateCallback callback,
545                                                 void* data) {
546     AChoreographer_to_Choreographer(choreographer)->registerRefreshRateCallback(callback, data);
547 }
AChoreographer_unregisterRefreshRateCallback(AChoreographer * choreographer,AChoreographer_refreshRateCallback callback,void * data)548 void AChoreographer_unregisterRefreshRateCallback(AChoreographer* choreographer,
549                                                   AChoreographer_refreshRateCallback callback,
550                                                   void* data) {
551     AChoreographer_to_Choreographer(choreographer)->unregisterRefreshRateCallback(callback, data);
552 }
553 
AChoreographer_create()554 AChoreographer* AChoreographer_create() {
555     Choreographer* choreographer = new Choreographer(nullptr);
556     status_t result = choreographer->initialize();
557     if (result != OK) {
558         ALOGW("Failed to initialize");
559         return nullptr;
560     }
561     return Choreographer_to_AChoreographer(choreographer);
562 }
563 
AChoreographer_destroy(AChoreographer * choreographer)564 void AChoreographer_destroy(AChoreographer* choreographer) {
565     if (choreographer == nullptr) {
566         return;
567     }
568 
569     delete AChoreographer_to_Choreographer(choreographer);
570 }
571 
AChoreographer_getFd(const AChoreographer * choreographer)572 int AChoreographer_getFd(const AChoreographer* choreographer) {
573     return AChoreographer_to_Choreographer(choreographer)->getFd();
574 }
575 
AChoreographer_handlePendingEvents(AChoreographer * choreographer,void * data)576 void AChoreographer_handlePendingEvents(AChoreographer* choreographer, void* data) {
577     // Pass dummy fd and events args to handleEvent, since the underlying
578     // DisplayEventDispatcher doesn't need them outside of validating that a
579     // Looper instance didn't break, but these args circumvent those checks.
580     Choreographer* impl = AChoreographer_to_Choreographer(choreographer);
581     impl->handleEvent(-1, Looper::EVENT_INPUT, data);
582 }
583