blob: 4c4a34f7e2616d185ae6959d3e4cf00c166b80df [file] [log] [blame]
Alec Mouricc445222019-10-22 10:19:17 -07001/*
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
Alec Mouri271de042020-04-27 22:38:19 -070020#include <android-base/thread_annotations.h>
Alec Mouri77a53872019-10-28 16:44:36 -070021#include <gui/DisplayEventDispatcher.h>
Alec Mouricc445222019-10-22 10:19:17 -070022#include <gui/ISurfaceComposer.h>
Orion Hodsone53587b2021-02-02 15:33:33 +000023#include <jni.h>
Alec Mouri271de042020-04-27 22:38:19 -070024#include <private/android/choreographer.h>
Alec Mouricc445222019-10-22 10:19:17 -070025#include <utils/Looper.h>
Alec Mouricc445222019-10-22 10:19:17 -070026#include <utils/Timers.h>
27
Alec Mouri60aee1c2019-10-28 16:18:59 -070028#include <cinttypes>
Alec Mouri271de042020-04-27 22:38:19 -070029#include <mutex>
Alec Mouri60aee1c2019-10-28 16:18:59 -070030#include <optional>
31#include <queue>
32#include <thread>
33
Alec Mouri271de042020-04-27 22:38:19 -070034namespace {
35struct {
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;
Alec Mouricc445222019-10-22 10:19:17 -070045
Alec Mouri271de042020-04-27 22:38:19 -070046// Gets the JNIEnv* for this thread, and performs one-off initialization if we
47// have never retrieved a JNIEnv* pointer before.
48JNIEnv* 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
70inline const char* toString(bool value) {
Alec Mouricc445222019-10-22 10:19:17 -070071 return value ? "true" : "false";
72}
Alec Mouri271de042020-04-27 22:38:19 -070073} // namespace
74
75namespace android {
Alec Mouricc445222019-10-22 10:19:17 -070076
77struct FrameCallback {
78 AChoreographer_frameCallback callback;
79 AChoreographer_frameCallback64 callback64;
Rachel Lee4879d812021-08-25 11:50:11 -070080 AChoreographer_extendedFrameCallback extendedCallback;
Alec Mouricc445222019-10-22 10:19:17 -070081 void* data;
82 nsecs_t dueTime;
83
84 inline bool operator<(const FrameCallback& rhs) const {
85 // Note that this is intentionally flipped because we want callbacks due sooner to be at
86 // the head of the queue
87 return dueTime > rhs.dueTime;
88 }
89};
90
Alec Mouri60aee1c2019-10-28 16:18:59 -070091struct RefreshRateCallback {
92 AChoreographer_refreshRateCallback callback;
93 void* data;
Alec Mouri271de042020-04-27 22:38:19 -070094 bool firstCallbackFired = false;
Alec Mouri60aee1c2019-10-28 16:18:59 -070095};
Alec Mouricc445222019-10-22 10:19:17 -070096
Alec Mouri271de042020-04-27 22:38:19 -070097class Choreographer;
98
Rachel Lee4879d812021-08-25 11:50:11 -070099/**
100 * Implementation of AChoreographerFrameCallbackData.
101 */
102struct ChoreographerFrameCallbackDataImpl {
103 struct FrameTimeline {
104 int64_t vsyncId{0};
105 int64_t expectedPresentTimeNanos{0};
106 int64_t deadlineNanos{0};
107 };
108
109 int64_t frameTimeNanos{0};
110
111 size_t frameTimelinesLength;
112
113 std::vector<FrameTimeline> frameTimelines;
114
115 size_t preferredFrameTimelineIndex;
116
117 const Choreographer* choreographer;
118};
119
Alec Mouri271de042020-04-27 22:38:19 -0700120struct {
121 std::mutex lock;
122 std::vector<Choreographer*> ptrs GUARDED_BY(lock);
123 bool registeredToDisplayManager GUARDED_BY(lock) = false;
124
125 std::atomic<nsecs_t> mLastKnownVsync = -1;
126} gChoreographers;
127
Alec Mouricc445222019-10-22 10:19:17 -0700128class Choreographer : public DisplayEventDispatcher, public MessageHandler {
129public:
Alec Mouri271de042020-04-27 22:38:19 -0700130 explicit Choreographer(const sp<Looper>& looper) EXCLUDES(gChoreographers.lock);
Alec Mouricc445222019-10-22 10:19:17 -0700131 void postFrameCallbackDelayed(AChoreographer_frameCallback cb,
Rachel Lee4879d812021-08-25 11:50:11 -0700132 AChoreographer_frameCallback64 cb64,
133 AChoreographer_extendedFrameCallback extendedCallback, void* data,
134 nsecs_t delay);
Alec Mouri271de042020-04-27 22:38:19 -0700135 void registerRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data)
136 EXCLUDES(gChoreographers.lock);
Alec Mouri33682e92020-01-10 15:11:15 -0800137 void unregisterRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data);
Alec Mouri271de042020-04-27 22:38:19 -0700138 // Drains the queue of pending vsync periods and dispatches refresh rate
139 // updates to callbacks.
140 // The assumption is that this method is only called on a single
141 // processing thread, either by looper or by AChoreographer_handleEvents
142 void handleRefreshRateUpdates();
143 void scheduleLatestConfigRequest();
Alec Mouricc445222019-10-22 10:19:17 -0700144
145 enum {
146 MSG_SCHEDULE_CALLBACKS = 0,
Alec Mouri271de042020-04-27 22:38:19 -0700147 MSG_SCHEDULE_VSYNC = 1,
148 MSG_HANDLE_REFRESH_RATE_UPDATES = 2,
Alec Mouricc445222019-10-22 10:19:17 -0700149 };
150 virtual void handleMessage(const Message& message) override;
151
152 static Choreographer* getForThread();
Alec Mouri271de042020-04-27 22:38:19 -0700153 virtual ~Choreographer() override EXCLUDES(gChoreographers.lock);
Ady Abraham74e17562020-08-24 18:18:19 -0700154 int64_t getVsyncId() const;
Ady Abraham0d28d762020-10-05 17:50:41 -0700155 int64_t getFrameDeadline() const;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100156 int64_t getFrameInterval() const;
Rachel Lee4879d812021-08-25 11:50:11 -0700157 bool inCallback() const;
Alec Mouricc445222019-10-22 10:19:17 -0700158
159private:
Alec Mouricc445222019-10-22 10:19:17 -0700160 Choreographer(const Choreographer&) = delete;
161
Ady Abraham74e17562020-08-24 18:18:19 -0700162 void dispatchVsync(nsecs_t timestamp, PhysicalDisplayId displayId, uint32_t count,
Ady Abraham0d28d762020-10-05 17:50:41 -0700163 VsyncEventData vsyncEventData) override;
Alec Mouricc445222019-10-22 10:19:17 -0700164 void dispatchHotplug(nsecs_t timestamp, PhysicalDisplayId displayId, bool connected) override;
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100165 void dispatchModeChanged(nsecs_t timestamp, PhysicalDisplayId displayId, int32_t modeId,
166 nsecs_t vsyncPeriod) override;
Alec Mouri967d5d72020-08-05 12:50:03 -0700167 void dispatchNullEvent(nsecs_t, PhysicalDisplayId) override;
Ady Abraham62f216c2020-10-13 19:07:23 -0700168 void dispatchFrameRateOverrides(nsecs_t timestamp, PhysicalDisplayId displayId,
169 std::vector<FrameRateOverride> overrides) override;
Alec Mouricc445222019-10-22 10:19:17 -0700170
171 void scheduleCallbacks();
172
Rachel Lee4879d812021-08-25 11:50:11 -0700173 ChoreographerFrameCallbackDataImpl createFrameCallbackData(nsecs_t timestamp) const;
174
Alec Mouri271de042020-04-27 22:38:19 -0700175 std::mutex mLock;
Alec Mouricc445222019-10-22 10:19:17 -0700176 // Protected by mLock
Alec Mouri60aee1c2019-10-28 16:18:59 -0700177 std::priority_queue<FrameCallback> mFrameCallbacks;
Alec Mouri60aee1c2019-10-28 16:18:59 -0700178 std::vector<RefreshRateCallback> mRefreshRateCallbacks;
Alec Mouricc445222019-10-22 10:19:17 -0700179
Alec Mouri271de042020-04-27 22:38:19 -0700180 nsecs_t mLatestVsyncPeriod = -1;
Ady Abraham0d28d762020-10-05 17:50:41 -0700181 VsyncEventData mLastVsyncEventData;
Rachel Lee4879d812021-08-25 11:50:11 -0700182 bool mInCallback = false;
Alec Mouricc445222019-10-22 10:19:17 -0700183
184 const sp<Looper> mLooper;
185 const std::thread::id mThreadId;
186};
187
Alec Mouricc445222019-10-22 10:19:17 -0700188static thread_local Choreographer* gChoreographer;
189Choreographer* Choreographer::getForThread() {
190 if (gChoreographer == nullptr) {
191 sp<Looper> looper = Looper::getForThread();
192 if (!looper.get()) {
193 ALOGW("No looper prepared for thread");
194 return nullptr;
195 }
196 gChoreographer = new Choreographer(looper);
197 status_t result = gChoreographer->initialize();
198 if (result != OK) {
199 ALOGW("Failed to initialize");
200 return nullptr;
201 }
202 }
203 return gChoreographer;
204}
205
Alec Mouri60aee1c2019-10-28 16:18:59 -0700206Choreographer::Choreographer(const sp<Looper>& looper)
Ady Abraham62f216c2020-10-13 19:07:23 -0700207 : DisplayEventDispatcher(looper, ISurfaceComposer::VsyncSource::eVsyncSourceApp),
Alec Mouri60aee1c2019-10-28 16:18:59 -0700208 mLooper(looper),
Alec Mouri271de042020-04-27 22:38:19 -0700209 mThreadId(std::this_thread::get_id()) {
210 std::lock_guard<std::mutex> _l(gChoreographers.lock);
211 gChoreographers.ptrs.push_back(this);
212}
213
214Choreographer::~Choreographer() {
215 std::lock_guard<std::mutex> _l(gChoreographers.lock);
216 gChoreographers.ptrs.erase(std::remove_if(gChoreographers.ptrs.begin(),
217 gChoreographers.ptrs.end(),
218 [=](Choreographer* c) { return c == this; }),
219 gChoreographers.ptrs.end());
220 // Only poke DisplayManagerGlobal to unregister if we previously registered
221 // callbacks.
222 if (gChoreographers.ptrs.empty() && gChoreographers.registeredToDisplayManager) {
Ady Abraham6a8986b2021-08-18 13:44:14 -0700223 gChoreographers.registeredToDisplayManager = false;
Alec Mouri271de042020-04-27 22:38:19 -0700224 JNIEnv* env = getJniEnv();
225 if (env == nullptr) {
226 ALOGW("JNI environment is unavailable, skipping choreographer cleanup");
227 return;
228 }
229 jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
230 gJni.displayManagerGlobal.getInstance);
231 if (dmg == nullptr) {
232 ALOGW("DMS is not initialized yet, skipping choreographer cleanup");
233 } else {
234 env->CallVoidMethod(dmg,
235 gJni.displayManagerGlobal
236 .unregisterNativeChoreographerForRefreshRateCallbacks);
237 env->DeleteLocalRef(dmg);
238 }
239 }
240}
Alec Mouricc445222019-10-22 10:19:17 -0700241
Rachel Lee4879d812021-08-25 11:50:11 -0700242void Choreographer::postFrameCallbackDelayed(AChoreographer_frameCallback cb,
243 AChoreographer_frameCallback64 cb64,
244 AChoreographer_extendedFrameCallback extendedCallback,
245 void* data, nsecs_t delay) {
Alec Mouricc445222019-10-22 10:19:17 -0700246 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Rachel Lee4879d812021-08-25 11:50:11 -0700247 FrameCallback callback{cb, cb64, extendedCallback, data, now + delay};
Alec Mouricc445222019-10-22 10:19:17 -0700248 {
Alec Mouri271de042020-04-27 22:38:19 -0700249 std::lock_guard<std::mutex> _l{mLock};
Alec Mouri60aee1c2019-10-28 16:18:59 -0700250 mFrameCallbacks.push(callback);
Alec Mouricc445222019-10-22 10:19:17 -0700251 }
252 if (callback.dueTime <= now) {
253 if (std::this_thread::get_id() != mThreadId) {
Alec Mouri50a931d2019-11-19 16:23:59 -0800254 if (mLooper != nullptr) {
255 Message m{MSG_SCHEDULE_VSYNC};
256 mLooper->sendMessage(this, m);
257 } else {
258 scheduleVsync();
259 }
Alec Mouricc445222019-10-22 10:19:17 -0700260 } else {
261 scheduleVsync();
262 }
263 } else {
Alec Mouri50a931d2019-11-19 16:23:59 -0800264 if (mLooper != nullptr) {
265 Message m{MSG_SCHEDULE_CALLBACKS};
266 mLooper->sendMessageDelayed(delay, this, m);
267 } else {
268 scheduleCallbacks();
269 }
Alec Mouricc445222019-10-22 10:19:17 -0700270 }
271}
272
Alec Mouri60aee1c2019-10-28 16:18:59 -0700273void Choreographer::registerRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data) {
Alec Mouri271de042020-04-27 22:38:19 -0700274 std::lock_guard<std::mutex> _l{mLock};
275 for (const auto& callback : mRefreshRateCallbacks) {
276 // Don't re-add callbacks.
277 if (cb == callback.callback && data == callback.data) {
278 return;
279 }
280 }
281 mRefreshRateCallbacks.emplace_back(
282 RefreshRateCallback{.callback = cb, .data = data, .firstCallbackFired = false});
283 bool needsRegistration = false;
Alec Mouri60aee1c2019-10-28 16:18:59 -0700284 {
Alec Mouri271de042020-04-27 22:38:19 -0700285 std::lock_guard<std::mutex> _l2(gChoreographers.lock);
286 needsRegistration = !gChoreographers.registeredToDisplayManager;
287 }
288 if (needsRegistration) {
289 JNIEnv* env = getJniEnv();
Alec Mouri271de042020-04-27 22:38:19 -0700290 if (env == nullptr) {
Greg Kaiserb66d04b2020-05-11 06:52:15 -0700291 ALOGW("JNI environment is unavailable, skipping registration");
Alec Mouri271de042020-04-27 22:38:19 -0700292 return;
293 }
Greg Kaiserb66d04b2020-05-11 06:52:15 -0700294 jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
295 gJni.displayManagerGlobal.getInstance);
Alec Mouri271de042020-04-27 22:38:19 -0700296 if (dmg == nullptr) {
297 ALOGW("DMS is not initialized yet: skipping registration");
298 return;
299 } else {
300 env->CallVoidMethod(dmg,
301 gJni.displayManagerGlobal
302 .registerNativeChoreographerForRefreshRateCallbacks,
303 reinterpret_cast<int64_t>(this));
304 env->DeleteLocalRef(dmg);
305 {
306 std::lock_guard<std::mutex> _l2(gChoreographers.lock);
307 gChoreographers.registeredToDisplayManager = true;
Alec Mouri33682e92020-01-10 15:11:15 -0800308 }
309 }
Alec Mouri271de042020-04-27 22:38:19 -0700310 } else {
311 scheduleLatestConfigRequest();
Alec Mouri60aee1c2019-10-28 16:18:59 -0700312 }
313}
314
Alec Mouri33682e92020-01-10 15:11:15 -0800315void Choreographer::unregisterRefreshRateCallback(AChoreographer_refreshRateCallback cb,
316 void* data) {
Alec Mouri271de042020-04-27 22:38:19 -0700317 std::lock_guard<std::mutex> _l{mLock};
318 mRefreshRateCallbacks.erase(std::remove_if(mRefreshRateCallbacks.begin(),
319 mRefreshRateCallbacks.end(),
320 [&](const RefreshRateCallback& callback) {
321 return cb == callback.callback &&
322 data == callback.data;
323 }),
324 mRefreshRateCallbacks.end());
325}
326
327void Choreographer::scheduleLatestConfigRequest() {
328 if (mLooper != nullptr) {
329 Message m{MSG_HANDLE_REFRESH_RATE_UPDATES};
330 mLooper->sendMessage(this, m);
331 } else {
332 // If the looper thread is detached from Choreographer, then refresh rate
333 // changes will be handled in AChoreographer_handlePendingEvents, so we
Alec Mouri967d5d72020-08-05 12:50:03 -0700334 // need to wake up the looper thread by writing to the write-end of the
335 // socket the looper is listening on.
336 // Fortunately, these events are small so sending packets across the
337 // socket should be atomic across processes.
338 DisplayEventReceiver::Event event;
Dominik Laskowskif1833852021-03-23 15:06:50 -0700339 event.header =
340 DisplayEventReceiver::Event::Header{DisplayEventReceiver::DISPLAY_EVENT_NULL,
341 PhysicalDisplayId::fromPort(0), systemTime()};
Alec Mouri967d5d72020-08-05 12:50:03 -0700342 injectEvent(event);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700343 }
344}
345
Alec Mouricc445222019-10-22 10:19:17 -0700346void Choreographer::scheduleCallbacks() {
Alec Mouri134266b2020-03-03 19:22:29 -0800347 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
348 nsecs_t dueTime;
349 {
Alec Mouri271de042020-04-27 22:38:19 -0700350 std::lock_guard<std::mutex> _l{mLock};
Alec Mouri134266b2020-03-03 19:22:29 -0800351 // If there are no pending callbacks then don't schedule a vsync
352 if (mFrameCallbacks.empty()) {
353 return;
354 }
355 dueTime = mFrameCallbacks.top().dueTime;
356 }
357
358 if (dueTime <= now) {
Alec Mouricc445222019-10-22 10:19:17 -0700359 ALOGV("choreographer %p ~ scheduling vsync", this);
360 scheduleVsync();
361 return;
362 }
363}
364
Alec Mouri271de042020-04-27 22:38:19 -0700365void Choreographer::handleRefreshRateUpdates() {
366 std::vector<RefreshRateCallback> callbacks{};
367 const nsecs_t pendingPeriod = gChoreographers.mLastKnownVsync.load();
368 const nsecs_t lastPeriod = mLatestVsyncPeriod;
369 if (pendingPeriod > 0) {
370 mLatestVsyncPeriod = pendingPeriod;
371 }
372 {
373 std::lock_guard<std::mutex> _l{mLock};
374 for (auto& cb : mRefreshRateCallbacks) {
375 callbacks.push_back(cb);
376 cb.firstCallbackFired = true;
377 }
378 }
379
380 for (auto& cb : callbacks) {
381 if (!cb.firstCallbackFired || (pendingPeriod > 0 && pendingPeriod != lastPeriod)) {
382 cb.callback(pendingPeriod, cb.data);
383 }
384 }
385}
386
Alec Mouricc445222019-10-22 10:19:17 -0700387// TODO(b/74619554): The PhysicalDisplayId is ignored because SF only emits VSYNC events for the
388// internal display and DisplayEventReceiver::requestNextVsync only allows requesting VSYNC for
389// the internal display implicitly.
Ady Abraham0d28d762020-10-05 17:50:41 -0700390void Choreographer::dispatchVsync(nsecs_t timestamp, PhysicalDisplayId, uint32_t,
391 VsyncEventData vsyncEventData) {
Alec Mouricc445222019-10-22 10:19:17 -0700392 std::vector<FrameCallback> callbacks{};
393 {
Alec Mouri271de042020-04-27 22:38:19 -0700394 std::lock_guard<std::mutex> _l{mLock};
Alec Mouricc445222019-10-22 10:19:17 -0700395 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700396 while (!mFrameCallbacks.empty() && mFrameCallbacks.top().dueTime < now) {
397 callbacks.push_back(mFrameCallbacks.top());
398 mFrameCallbacks.pop();
Alec Mouricc445222019-10-22 10:19:17 -0700399 }
400 }
Ady Abraham0d28d762020-10-05 17:50:41 -0700401 mLastVsyncEventData = vsyncEventData;
Alec Mouricc445222019-10-22 10:19:17 -0700402 for (const auto& cb : callbacks) {
Rachel Lee4879d812021-08-25 11:50:11 -0700403 if (cb.extendedCallback != nullptr) {
404 const ChoreographerFrameCallbackDataImpl frameCallbackData =
405 createFrameCallbackData(timestamp);
406 mInCallback = true;
407 cb.extendedCallback(reinterpret_cast<const AChoreographerFrameCallbackData*>(
408 &frameCallbackData),
409 cb.data);
410 mInCallback = false;
411 } else if (cb.callback64 != nullptr) {
Alec Mouricc445222019-10-22 10:19:17 -0700412 cb.callback64(timestamp, cb.data);
413 } else if (cb.callback != nullptr) {
414 cb.callback(timestamp, cb.data);
415 }
416 }
417}
418
419void Choreographer::dispatchHotplug(nsecs_t, PhysicalDisplayId displayId, bool connected) {
Rachel Lee4879d812021-08-25 11:50:11 -0700420 ALOGV("choreographer %p ~ received hotplug event (displayId=%s, connected=%s), ignoring.", this,
421 to_string(displayId).c_str(), toString(connected));
Alec Mouricc445222019-10-22 10:19:17 -0700422}
423
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100424void Choreographer::dispatchModeChanged(nsecs_t, PhysicalDisplayId, int32_t, nsecs_t) {
425 LOG_ALWAYS_FATAL("dispatchModeChanged was called but was never registered");
Ady Abraham62f216c2020-10-13 19:07:23 -0700426}
427
428void Choreographer::dispatchFrameRateOverrides(nsecs_t, PhysicalDisplayId,
429 std::vector<FrameRateOverride>) {
430 LOG_ALWAYS_FATAL("dispatchFrameRateOverrides was called but was never registered");
Alec Mouri967d5d72020-08-05 12:50:03 -0700431}
Alec Mouri271de042020-04-27 22:38:19 -0700432
Alec Mouri967d5d72020-08-05 12:50:03 -0700433void Choreographer::dispatchNullEvent(nsecs_t, PhysicalDisplayId) {
434 ALOGV("choreographer %p ~ received null event.", this);
435 handleRefreshRateUpdates();
Alec Mouricc445222019-10-22 10:19:17 -0700436}
437
438void Choreographer::handleMessage(const Message& message) {
439 switch (message.what) {
Rachel Lee4879d812021-08-25 11:50:11 -0700440 case MSG_SCHEDULE_CALLBACKS:
441 scheduleCallbacks();
442 break;
443 case MSG_SCHEDULE_VSYNC:
444 scheduleVsync();
445 break;
446 case MSG_HANDLE_REFRESH_RATE_UPDATES:
447 handleRefreshRateUpdates();
448 break;
Alec Mouricc445222019-10-22 10:19:17 -0700449 }
450}
451
Ady Abraham74e17562020-08-24 18:18:19 -0700452int64_t Choreographer::getVsyncId() const {
Ady Abraham0d28d762020-10-05 17:50:41 -0700453 return mLastVsyncEventData.id;
454}
455
456int64_t Choreographer::getFrameDeadline() const {
457 return mLastVsyncEventData.deadlineTimestamp;
Ady Abraham74e17562020-08-24 18:18:19 -0700458}
459
Jorim Jaggic0086af2021-02-12 18:18:11 +0100460int64_t Choreographer::getFrameInterval() const {
461 return mLastVsyncEventData.frameInterval;
462}
463
Rachel Lee4879d812021-08-25 11:50:11 -0700464bool Choreographer::inCallback() const {
465 return mInCallback;
466}
467
468ChoreographerFrameCallbackDataImpl Choreographer::createFrameCallbackData(nsecs_t timestamp) const {
469 std::vector<ChoreographerFrameCallbackDataImpl::FrameTimeline> frameTimelines;
470 frameTimelines.push_back({.vsyncId = mLastVsyncEventData.id,
471 .expectedPresentTimeNanos = mLastVsyncEventData.expectedPresentTime,
472 .deadlineNanos = mLastVsyncEventData.deadlineTimestamp});
473 return {.frameTimeNanos = timestamp,
474 .frameTimelinesLength = 1,
475 .preferredFrameTimelineIndex = 0,
476 .frameTimelines = frameTimelines,
477 .choreographer = this};
478}
479
Alec Mouri271de042020-04-27 22:38:19 -0700480} // namespace android
Alec Mouri50a931d2019-11-19 16:23:59 -0800481using namespace android;
Alec Mouricc445222019-10-22 10:19:17 -0700482
483static inline Choreographer* AChoreographer_to_Choreographer(AChoreographer* choreographer) {
484 return reinterpret_cast<Choreographer*>(choreographer);
485}
486
Ady Abraham74e17562020-08-24 18:18:19 -0700487static inline const Choreographer* AChoreographer_to_Choreographer(
488 const AChoreographer* choreographer) {
489 return reinterpret_cast<const Choreographer*>(choreographer);
490}
491
Rachel Lee4879d812021-08-25 11:50:11 -0700492static inline const ChoreographerFrameCallbackDataImpl*
493AChoreographerFrameCallbackData_to_ChoreographerFrameCallbackDataImpl(
494 const AChoreographerFrameCallbackData* data) {
495 return reinterpret_cast<const ChoreographerFrameCallbackDataImpl*>(data);
496}
497
Alec Mouri271de042020-04-27 22:38:19 -0700498// Glue for private C api
499namespace android {
500void AChoreographer_signalRefreshRateCallbacks(nsecs_t vsyncPeriod) EXCLUDES(gChoreographers.lock) {
501 std::lock_guard<std::mutex> _l(gChoreographers.lock);
502 gChoreographers.mLastKnownVsync.store(vsyncPeriod);
503 for (auto c : gChoreographers.ptrs) {
504 c->scheduleLatestConfigRequest();
505 }
506}
507
508void AChoreographer_initJVM(JNIEnv* env) {
509 env->GetJavaVM(&gJni.jvm);
510 // Now we need to find the java classes.
511 jclass dmgClass = env->FindClass("android/hardware/display/DisplayManagerGlobal");
512 gJni.displayManagerGlobal.clazz = static_cast<jclass>(env->NewGlobalRef(dmgClass));
513 gJni.displayManagerGlobal.getInstance =
514 env->GetStaticMethodID(dmgClass, "getInstance",
515 "()Landroid/hardware/display/DisplayManagerGlobal;");
516 gJni.displayManagerGlobal.registerNativeChoreographerForRefreshRateCallbacks =
517 env->GetMethodID(dmgClass, "registerNativeChoreographerForRefreshRateCallbacks", "()V");
518 gJni.displayManagerGlobal.unregisterNativeChoreographerForRefreshRateCallbacks =
519 env->GetMethodID(dmgClass, "unregisterNativeChoreographerForRefreshRateCallbacks",
520 "()V");
521}
522
523AChoreographer* AChoreographer_routeGetInstance() {
524 return AChoreographer_getInstance();
525}
526void AChoreographer_routePostFrameCallback(AChoreographer* choreographer,
527 AChoreographer_frameCallback callback, void* data) {
Jiyong Park8cdf0762020-08-13 20:21:57 +0900528#pragma clang diagnostic push
529#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Alec Mouri271de042020-04-27 22:38:19 -0700530 return AChoreographer_postFrameCallback(choreographer, callback, data);
Jiyong Park8cdf0762020-08-13 20:21:57 +0900531#pragma clang diagnostic pop
Alec Mouri271de042020-04-27 22:38:19 -0700532}
533void AChoreographer_routePostFrameCallbackDelayed(AChoreographer* choreographer,
534 AChoreographer_frameCallback callback, void* data,
535 long delayMillis) {
Jiyong Park8cdf0762020-08-13 20:21:57 +0900536#pragma clang diagnostic push
537#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Alec Mouri271de042020-04-27 22:38:19 -0700538 return AChoreographer_postFrameCallbackDelayed(choreographer, callback, data, delayMillis);
Jiyong Park8cdf0762020-08-13 20:21:57 +0900539#pragma clang diagnostic pop
Alec Mouri271de042020-04-27 22:38:19 -0700540}
541void AChoreographer_routePostFrameCallback64(AChoreographer* choreographer,
542 AChoreographer_frameCallback64 callback, void* data) {
543 return AChoreographer_postFrameCallback64(choreographer, callback, data);
544}
545void AChoreographer_routePostFrameCallbackDelayed64(AChoreographer* choreographer,
546 AChoreographer_frameCallback64 callback,
547 void* data, uint32_t delayMillis) {
548 return AChoreographer_postFrameCallbackDelayed64(choreographer, callback, data, delayMillis);
549}
Rachel Lee4879d812021-08-25 11:50:11 -0700550void AChoreographer_routePostExtendedFrameCallback(AChoreographer* choreographer,
551 AChoreographer_extendedFrameCallback callback,
552 void* data) {
553 return AChoreographer_postExtendedFrameCallback(choreographer, callback, data);
554}
Alec Mouri271de042020-04-27 22:38:19 -0700555void AChoreographer_routeRegisterRefreshRateCallback(AChoreographer* choreographer,
556 AChoreographer_refreshRateCallback callback,
557 void* data) {
558 return AChoreographer_registerRefreshRateCallback(choreographer, callback, data);
559}
560void AChoreographer_routeUnregisterRefreshRateCallback(AChoreographer* choreographer,
561 AChoreographer_refreshRateCallback callback,
562 void* data) {
563 return AChoreographer_unregisterRefreshRateCallback(choreographer, callback, data);
564}
Rachel Lee4879d812021-08-25 11:50:11 -0700565int64_t AChoreographerFrameCallbackData_routeGetFrameTimeNanos(
566 const AChoreographerFrameCallbackData* data) {
567 return AChoreographerFrameCallbackData_getFrameTimeNanos(data);
568}
569size_t AChoreographerFrameCallbackData_routeGetFrameTimelinesLength(
570 const AChoreographerFrameCallbackData* data) {
571 return AChoreographerFrameCallbackData_getFrameTimelinesLength(data);
572}
573size_t AChoreographerFrameCallbackData_routeGetPreferredFrameTimelineIndex(
574 const AChoreographerFrameCallbackData* data) {
575 return AChoreographerFrameCallbackData_getPreferredFrameTimelineIndex(data);
576}
577int64_t AChoreographerFrameCallbackData_routeGetFrameTimelineVsyncId(
578 const AChoreographerFrameCallbackData* data, size_t index) {
579 return AChoreographerFrameCallbackData_getFrameTimelineVsyncId(data, index);
580}
581int64_t AChoreographerFrameCallbackData_routeGetFrameTimelineExpectedPresentTime(
582 const AChoreographerFrameCallbackData* data, size_t index) {
583 return AChoreographerFrameCallbackData_getFrameTimelineExpectedPresentTime(data, index);
584}
585int64_t AChoreographerFrameCallbackData_routeGetFrameTimelineDeadline(
586 const AChoreographerFrameCallbackData* data, size_t index) {
587 return AChoreographerFrameCallbackData_getFrameTimelineDeadline(data, index);
588}
Alec Mouri271de042020-04-27 22:38:19 -0700589
Ady Abraham74e17562020-08-24 18:18:19 -0700590int64_t AChoreographer_getVsyncId(const AChoreographer* choreographer) {
591 return AChoreographer_to_Choreographer(choreographer)->getVsyncId();
592}
593
Ady Abraham0d28d762020-10-05 17:50:41 -0700594int64_t AChoreographer_getFrameDeadline(const AChoreographer* choreographer) {
595 return AChoreographer_to_Choreographer(choreographer)->getFrameDeadline();
596}
597
Jorim Jaggic0086af2021-02-12 18:18:11 +0100598int64_t AChoreographer_getFrameInterval(const AChoreographer* choreographer) {
599 return AChoreographer_to_Choreographer(choreographer)->getFrameInterval();
600}
601
Alec Mouri271de042020-04-27 22:38:19 -0700602} // namespace android
603
604/* Glue for the NDK interface */
605
Alec Mouricc445222019-10-22 10:19:17 -0700606static inline AChoreographer* Choreographer_to_AChoreographer(Choreographer* choreographer) {
607 return reinterpret_cast<AChoreographer*>(choreographer);
608}
609
610AChoreographer* AChoreographer_getInstance() {
611 return Choreographer_to_AChoreographer(Choreographer::getForThread());
612}
613
614void AChoreographer_postFrameCallback(AChoreographer* choreographer,
Rachel Lee4879d812021-08-25 11:50:11 -0700615 AChoreographer_frameCallback callback, void* data) {
616 AChoreographer_to_Choreographer(choreographer)
617 ->postFrameCallbackDelayed(callback, nullptr, nullptr, data, 0);
Alec Mouricc445222019-10-22 10:19:17 -0700618}
619void AChoreographer_postFrameCallbackDelayed(AChoreographer* choreographer,
Rachel Lee4879d812021-08-25 11:50:11 -0700620 AChoreographer_frameCallback callback, void* data,
621 long delayMillis) {
622 AChoreographer_to_Choreographer(choreographer)
623 ->postFrameCallbackDelayed(callback, nullptr, nullptr, data, ms2ns(delayMillis));
624}
625void AChoreographer_postExtendedFrameCallback(AChoreographer* choreographer,
626 AChoreographer_extendedFrameCallback callback,
627 void* data) {
628 AChoreographer_to_Choreographer(choreographer)
629 ->postFrameCallbackDelayed(nullptr, nullptr, callback, data, 0);
Alec Mouricc445222019-10-22 10:19:17 -0700630}
631void AChoreographer_postFrameCallback64(AChoreographer* choreographer,
Rachel Lee4879d812021-08-25 11:50:11 -0700632 AChoreographer_frameCallback64 callback, void* data) {
633 AChoreographer_to_Choreographer(choreographer)
634 ->postFrameCallbackDelayed(nullptr, callback, nullptr, data, 0);
Alec Mouricc445222019-10-22 10:19:17 -0700635}
636void AChoreographer_postFrameCallbackDelayed64(AChoreographer* choreographer,
Rachel Lee4879d812021-08-25 11:50:11 -0700637 AChoreographer_frameCallback64 callback, void* data,
638 uint32_t delayMillis) {
639 AChoreographer_to_Choreographer(choreographer)
640 ->postFrameCallbackDelayed(nullptr, callback, nullptr, data, ms2ns(delayMillis));
Alec Mouricc445222019-10-22 10:19:17 -0700641}
Alec Mouri60aee1c2019-10-28 16:18:59 -0700642void AChoreographer_registerRefreshRateCallback(AChoreographer* choreographer,
643 AChoreographer_refreshRateCallback callback,
644 void* data) {
645 AChoreographer_to_Choreographer(choreographer)->registerRefreshRateCallback(callback, data);
646}
647void AChoreographer_unregisterRefreshRateCallback(AChoreographer* choreographer,
Alec Mouri33682e92020-01-10 15:11:15 -0800648 AChoreographer_refreshRateCallback callback,
649 void* data) {
650 AChoreographer_to_Choreographer(choreographer)->unregisterRefreshRateCallback(callback, data);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700651}
Alec Mouri50a931d2019-11-19 16:23:59 -0800652
Rachel Lee4879d812021-08-25 11:50:11 -0700653int64_t AChoreographerFrameCallbackData_getFrameTimeNanos(
654 const AChoreographerFrameCallbackData* data) {
655 const ChoreographerFrameCallbackDataImpl* frameCallbackData =
656 AChoreographerFrameCallbackData_to_ChoreographerFrameCallbackDataImpl(data);
657 LOG_ALWAYS_FATAL_IF(!frameCallbackData->choreographer->inCallback(),
658 "Data is only valid in callback");
659 return frameCallbackData->frameTimeNanos;
660}
661size_t AChoreographerFrameCallbackData_getFrameTimelinesLength(
662 const AChoreographerFrameCallbackData* data) {
663 const ChoreographerFrameCallbackDataImpl* frameCallbackData =
664 AChoreographerFrameCallbackData_to_ChoreographerFrameCallbackDataImpl(data);
665 LOG_ALWAYS_FATAL_IF(!frameCallbackData->choreographer->inCallback(),
666 "Data is only valid in callback");
667 return frameCallbackData->frameTimelinesLength;
668}
669size_t AChoreographerFrameCallbackData_getPreferredFrameTimelineIndex(
670 const AChoreographerFrameCallbackData* data) {
671 const ChoreographerFrameCallbackDataImpl* frameCallbackData =
672 AChoreographerFrameCallbackData_to_ChoreographerFrameCallbackDataImpl(data);
673 LOG_ALWAYS_FATAL_IF(!frameCallbackData->choreographer->inCallback(),
674 "Data is only valid in callback");
675 return frameCallbackData->preferredFrameTimelineIndex;
676}
677int64_t AChoreographerFrameCallbackData_getFrameTimelineVsyncId(
678 const AChoreographerFrameCallbackData* data, size_t index) {
679 const ChoreographerFrameCallbackDataImpl* frameCallbackData =
680 AChoreographerFrameCallbackData_to_ChoreographerFrameCallbackDataImpl(data);
681 LOG_ALWAYS_FATAL_IF(!frameCallbackData->choreographer->inCallback(),
682 "Data is only valid in callback");
683 LOG_ALWAYS_FATAL_IF(index >= frameCallbackData->frameTimelinesLength, "Index out of bounds");
684 return frameCallbackData->frameTimelines[index].vsyncId;
685}
686int64_t AChoreographerFrameCallbackData_getFrameTimelineExpectedPresentTime(
687 const AChoreographerFrameCallbackData* data, size_t index) {
688 const ChoreographerFrameCallbackDataImpl* frameCallbackData =
689 AChoreographerFrameCallbackData_to_ChoreographerFrameCallbackDataImpl(data);
690 LOG_ALWAYS_FATAL_IF(!frameCallbackData->choreographer->inCallback(),
691 "Data is only valid in callback");
692 LOG_ALWAYS_FATAL_IF(index >= frameCallbackData->frameTimelinesLength, "Index out of bounds");
693 return frameCallbackData->frameTimelines[index].expectedPresentTimeNanos;
694}
695int64_t AChoreographerFrameCallbackData_getFrameTimelineDeadline(
696 const AChoreographerFrameCallbackData* data, size_t index) {
697 const ChoreographerFrameCallbackDataImpl* frameCallbackData =
698 AChoreographerFrameCallbackData_to_ChoreographerFrameCallbackDataImpl(data);
699 LOG_ALWAYS_FATAL_IF(!frameCallbackData->choreographer->inCallback(),
700 "Data is only valid in callback");
701 LOG_ALWAYS_FATAL_IF(index >= frameCallbackData->frameTimelinesLength, "Index out of bounds");
702 return frameCallbackData->frameTimelines[index].deadlineNanos;
703}
704
Alec Mouri50a931d2019-11-19 16:23:59 -0800705AChoreographer* AChoreographer_create() {
706 Choreographer* choreographer = new Choreographer(nullptr);
707 status_t result = choreographer->initialize();
708 if (result != OK) {
709 ALOGW("Failed to initialize");
710 return nullptr;
711 }
712 return Choreographer_to_AChoreographer(choreographer);
713}
714
715void AChoreographer_destroy(AChoreographer* choreographer) {
716 if (choreographer == nullptr) {
717 return;
718 }
719
720 delete AChoreographer_to_Choreographer(choreographer);
721}
722
Alec Mouri921b2772020-02-05 19:03:28 -0800723int AChoreographer_getFd(const AChoreographer* choreographer) {
Alec Mouri50a931d2019-11-19 16:23:59 -0800724 return AChoreographer_to_Choreographer(choreographer)->getFd();
725}
726
727void AChoreographer_handlePendingEvents(AChoreographer* choreographer, void* data) {
728 // Pass dummy fd and events args to handleEvent, since the underlying
729 // DisplayEventDispatcher doesn't need them outside of validating that a
730 // Looper instance didn't break, but these args circumvent those checks.
Alec Mouri271de042020-04-27 22:38:19 -0700731 Choreographer* impl = AChoreographer_to_Choreographer(choreographer);
732 impl->handleEvent(-1, Looper::EVENT_INPUT, data);
Alec Mouri50a931d2019-11-19 16:23:59 -0800733}