blob: 6b25b262c34521ea190f3c98640d33619634c5fe [file] [log] [blame]
Rachel Leeace701c2022-10-05 10:23:47 -07001/*
2 * Copyright 2022 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_NDEBUG 0
18
Rachel Lee273c18c2022-12-13 14:35:07 -080019#include <gui/Choreographer.h>
Rachel Leeace701c2022-10-05 10:23:47 -070020#include <jni.h>
Rachel Leeace701c2022-10-05 10:23:47 -070021
22#undef LOG_TAG
23#define LOG_TAG "AChoreographer"
24
25namespace {
26struct {
27 // Global JVM that is provided by zygote
28 JavaVM* jvm = nullptr;
29 struct {
30 jclass clazz;
31 jmethodID getInstance;
32 jmethodID registerNativeChoreographerForRefreshRateCallbacks;
33 jmethodID unregisterNativeChoreographerForRefreshRateCallbacks;
34 } displayManagerGlobal;
35} gJni;
36
37// Gets the JNIEnv* for this thread, and performs one-off initialization if we
38// have never retrieved a JNIEnv* pointer before.
39JNIEnv* getJniEnv() {
40 if (gJni.jvm == nullptr) {
41 ALOGW("AChoreographer: No JVM provided!");
42 return nullptr;
43 }
44
45 JNIEnv* env = nullptr;
46 if (gJni.jvm->GetEnv((void**)&env, JNI_VERSION_1_4) != JNI_OK) {
47 ALOGD("Attaching thread to JVM for AChoreographer");
48 JavaVMAttachArgs args = {JNI_VERSION_1_4, "AChoreographer_env", NULL};
49 jint attachResult = gJni.jvm->AttachCurrentThreadAsDaemon(&env, (void*)&args);
50 if (attachResult != JNI_OK) {
51 ALOGE("Unable to attach thread. Error: %d", attachResult);
52 return nullptr;
53 }
54 }
55 if (env == nullptr) {
56 ALOGW("AChoreographer: No JNI env available!");
57 }
58 return env;
59}
60
61inline const char* toString(bool value) {
62 return value ? "true" : "false";
63}
64} // namespace
65
66namespace android {
67
68Choreographer::Context Choreographer::gChoreographers;
69
70static thread_local Choreographer* gChoreographer;
71
72void Choreographer::initJVM(JNIEnv* env) {
73 env->GetJavaVM(&gJni.jvm);
74 // Now we need to find the java classes.
75 jclass dmgClass = env->FindClass("android/hardware/display/DisplayManagerGlobal");
76 gJni.displayManagerGlobal.clazz = static_cast<jclass>(env->NewGlobalRef(dmgClass));
77 gJni.displayManagerGlobal.getInstance =
78 env->GetStaticMethodID(dmgClass, "getInstance",
79 "()Landroid/hardware/display/DisplayManagerGlobal;");
80 gJni.displayManagerGlobal.registerNativeChoreographerForRefreshRateCallbacks =
81 env->GetMethodID(dmgClass, "registerNativeChoreographerForRefreshRateCallbacks", "()V");
82 gJni.displayManagerGlobal.unregisterNativeChoreographerForRefreshRateCallbacks =
83 env->GetMethodID(dmgClass, "unregisterNativeChoreographerForRefreshRateCallbacks",
84 "()V");
85}
86
87Choreographer* Choreographer::getForThread() {
88 if (gChoreographer == nullptr) {
89 sp<Looper> looper = Looper::getForThread();
90 if (!looper.get()) {
91 ALOGW("No looper prepared for thread");
92 return nullptr;
93 }
94 gChoreographer = new Choreographer(looper);
95 status_t result = gChoreographer->initialize();
96 if (result != OK) {
97 ALOGW("Failed to initialize");
98 return nullptr;
99 }
100 }
101 return gChoreographer;
102}
103
104Choreographer::Choreographer(const sp<Looper>& looper)
105 : DisplayEventDispatcher(looper, gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp),
106 mLooper(looper),
107 mThreadId(std::this_thread::get_id()) {
108 std::lock_guard<std::mutex> _l(gChoreographers.lock);
109 gChoreographers.ptrs.push_back(this);
110}
111
112Choreographer::~Choreographer() {
113 std::lock_guard<std::mutex> _l(gChoreographers.lock);
114 gChoreographers.ptrs.erase(std::remove_if(gChoreographers.ptrs.begin(),
115 gChoreographers.ptrs.end(),
116 [=](Choreographer* c) { return c == this; }),
117 gChoreographers.ptrs.end());
118 // Only poke DisplayManagerGlobal to unregister if we previously registered
119 // callbacks.
120 if (gChoreographers.ptrs.empty() && gChoreographers.registeredToDisplayManager) {
121 gChoreographers.registeredToDisplayManager = false;
122 JNIEnv* env = getJniEnv();
123 if (env == nullptr) {
124 ALOGW("JNI environment is unavailable, skipping choreographer cleanup");
125 return;
126 }
127 jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
128 gJni.displayManagerGlobal.getInstance);
129 if (dmg == nullptr) {
130 ALOGW("DMS is not initialized yet, skipping choreographer cleanup");
131 } else {
132 env->CallVoidMethod(dmg,
133 gJni.displayManagerGlobal
134 .unregisterNativeChoreographerForRefreshRateCallbacks);
135 env->DeleteLocalRef(dmg);
136 }
137 }
138}
139
140void Choreographer::postFrameCallbackDelayed(AChoreographer_frameCallback cb,
141 AChoreographer_frameCallback64 cb64,
142 AChoreographer_vsyncCallback vsyncCallback, void* data,
143 nsecs_t delay) {
144 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
145 FrameCallback callback{cb, cb64, vsyncCallback, data, now + delay};
146 {
147 std::lock_guard<std::mutex> _l{mLock};
148 mFrameCallbacks.push(callback);
149 }
150 if (callback.dueTime <= now) {
151 if (std::this_thread::get_id() != mThreadId) {
152 if (mLooper != nullptr) {
153 Message m{MSG_SCHEDULE_VSYNC};
154 mLooper->sendMessage(this, m);
155 } else {
156 scheduleVsync();
157 }
158 } else {
159 scheduleVsync();
160 }
161 } else {
162 if (mLooper != nullptr) {
163 Message m{MSG_SCHEDULE_CALLBACKS};
164 mLooper->sendMessageDelayed(delay, this, m);
165 } else {
166 scheduleCallbacks();
167 }
168 }
169}
170
171void Choreographer::registerRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data) {
172 std::lock_guard<std::mutex> _l{mLock};
173 for (const auto& callback : mRefreshRateCallbacks) {
174 // Don't re-add callbacks.
175 if (cb == callback.callback && data == callback.data) {
176 return;
177 }
178 }
179 mRefreshRateCallbacks.emplace_back(
180 RefreshRateCallback{.callback = cb, .data = data, .firstCallbackFired = false});
181 bool needsRegistration = false;
182 {
183 std::lock_guard<std::mutex> _l2(gChoreographers.lock);
184 needsRegistration = !gChoreographers.registeredToDisplayManager;
185 }
186 if (needsRegistration) {
187 JNIEnv* env = getJniEnv();
188 if (env == nullptr) {
189 ALOGW("JNI environment is unavailable, skipping registration");
190 return;
191 }
192 jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
193 gJni.displayManagerGlobal.getInstance);
194 if (dmg == nullptr) {
195 ALOGW("DMS is not initialized yet: skipping registration");
196 return;
197 } else {
198 env->CallVoidMethod(dmg,
199 gJni.displayManagerGlobal
200 .registerNativeChoreographerForRefreshRateCallbacks,
201 reinterpret_cast<int64_t>(this));
202 env->DeleteLocalRef(dmg);
203 {
204 std::lock_guard<std::mutex> _l2(gChoreographers.lock);
205 gChoreographers.registeredToDisplayManager = true;
206 }
207 }
208 } else {
209 scheduleLatestConfigRequest();
210 }
211}
212
213void Choreographer::unregisterRefreshRateCallback(AChoreographer_refreshRateCallback cb,
214 void* data) {
215 std::lock_guard<std::mutex> _l{mLock};
216 mRefreshRateCallbacks.erase(std::remove_if(mRefreshRateCallbacks.begin(),
217 mRefreshRateCallbacks.end(),
218 [&](const RefreshRateCallback& callback) {
219 return cb == callback.callback &&
220 data == callback.data;
221 }),
222 mRefreshRateCallbacks.end());
223}
224
225void Choreographer::scheduleLatestConfigRequest() {
226 if (mLooper != nullptr) {
227 Message m{MSG_HANDLE_REFRESH_RATE_UPDATES};
228 mLooper->sendMessage(this, m);
229 } else {
230 // If the looper thread is detached from Choreographer, then refresh rate
231 // changes will be handled in AChoreographer_handlePendingEvents, so we
232 // need to wake up the looper thread by writing to the write-end of the
233 // socket the looper is listening on.
234 // Fortunately, these events are small so sending packets across the
235 // socket should be atomic across processes.
236 DisplayEventReceiver::Event event;
237 event.header =
238 DisplayEventReceiver::Event::Header{DisplayEventReceiver::DISPLAY_EVENT_NULL,
239 PhysicalDisplayId::fromPort(0), systemTime()};
240 injectEvent(event);
241 }
242}
243
244void Choreographer::scheduleCallbacks() {
245 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
246 nsecs_t dueTime;
247 {
248 std::lock_guard<std::mutex> _l{mLock};
249 // If there are no pending callbacks then don't schedule a vsync
250 if (mFrameCallbacks.empty()) {
251 return;
252 }
253 dueTime = mFrameCallbacks.top().dueTime;
254 }
255
256 if (dueTime <= now) {
257 ALOGV("choreographer %p ~ scheduling vsync", this);
258 scheduleVsync();
259 return;
260 }
261}
262
263void Choreographer::handleRefreshRateUpdates() {
264 std::vector<RefreshRateCallback> callbacks{};
265 const nsecs_t pendingPeriod = gChoreographers.mLastKnownVsync.load();
266 const nsecs_t lastPeriod = mLatestVsyncPeriod;
267 if (pendingPeriod > 0) {
268 mLatestVsyncPeriod = pendingPeriod;
269 }
270 {
271 std::lock_guard<std::mutex> _l{mLock};
272 for (auto& cb : mRefreshRateCallbacks) {
273 callbacks.push_back(cb);
274 cb.firstCallbackFired = true;
275 }
276 }
277
278 for (auto& cb : callbacks) {
279 if (!cb.firstCallbackFired || (pendingPeriod > 0 && pendingPeriod != lastPeriod)) {
280 cb.callback(pendingPeriod, cb.data);
281 }
282 }
283}
284
285void Choreographer::dispatchVsync(nsecs_t timestamp, PhysicalDisplayId, uint32_t,
286 VsyncEventData vsyncEventData) {
287 std::vector<FrameCallback> callbacks{};
288 {
289 std::lock_guard<std::mutex> _l{mLock};
290 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
291 while (!mFrameCallbacks.empty() && mFrameCallbacks.top().dueTime < now) {
292 callbacks.push_back(mFrameCallbacks.top());
293 mFrameCallbacks.pop();
294 }
295 }
296 mLastVsyncEventData = vsyncEventData;
297 for (const auto& cb : callbacks) {
298 if (cb.vsyncCallback != nullptr) {
299 const ChoreographerFrameCallbackDataImpl frameCallbackData =
300 createFrameCallbackData(timestamp);
301 registerStartTime();
302 mInCallback = true;
303 cb.vsyncCallback(reinterpret_cast<const AChoreographerFrameCallbackData*>(
304 &frameCallbackData),
305 cb.data);
306 mInCallback = false;
307 } else if (cb.callback64 != nullptr) {
308 cb.callback64(timestamp, cb.data);
309 } else if (cb.callback != nullptr) {
310 cb.callback(timestamp, cb.data);
311 }
312 }
313}
314
315void Choreographer::dispatchHotplug(nsecs_t, PhysicalDisplayId displayId, bool connected) {
316 ALOGV("choreographer %p ~ received hotplug event (displayId=%s, connected=%s), ignoring.", this,
317 to_string(displayId).c_str(), toString(connected));
318}
319
320void Choreographer::dispatchModeChanged(nsecs_t, PhysicalDisplayId, int32_t, nsecs_t) {
321 LOG_ALWAYS_FATAL("dispatchModeChanged was called but was never registered");
322}
323
324void Choreographer::dispatchFrameRateOverrides(nsecs_t, PhysicalDisplayId,
325 std::vector<FrameRateOverride>) {
326 LOG_ALWAYS_FATAL("dispatchFrameRateOverrides was called but was never registered");
327}
328
329void Choreographer::dispatchNullEvent(nsecs_t, PhysicalDisplayId) {
330 ALOGV("choreographer %p ~ received null event.", this);
331 handleRefreshRateUpdates();
332}
333
334void Choreographer::handleMessage(const Message& message) {
335 switch (message.what) {
336 case MSG_SCHEDULE_CALLBACKS:
337 scheduleCallbacks();
338 break;
339 case MSG_SCHEDULE_VSYNC:
340 scheduleVsync();
341 break;
342 case MSG_HANDLE_REFRESH_RATE_UPDATES:
343 handleRefreshRateUpdates();
344 break;
345 }
346}
347
348int64_t Choreographer::getFrameInterval() const {
349 return mLastVsyncEventData.frameInterval;
350}
351
352bool Choreographer::inCallback() const {
353 return mInCallback;
354}
355
356ChoreographerFrameCallbackDataImpl Choreographer::createFrameCallbackData(nsecs_t timestamp) const {
357 return {.frameTimeNanos = timestamp,
358 .vsyncEventData = mLastVsyncEventData,
359 .choreographer = this};
360}
361
362void Choreographer::registerStartTime() const {
363 std::scoped_lock _l(gChoreographers.lock);
364 for (VsyncEventData::FrameTimeline frameTimeline : mLastVsyncEventData.frameTimelines) {
365 while (gChoreographers.startTimes.size() >= kMaxStartTimes) {
366 gChoreographers.startTimes.erase(gChoreographers.startTimes.begin());
367 }
368 gChoreographers.startTimes[frameTimeline.vsyncId] = systemTime(SYSTEM_TIME_MONOTONIC);
369 }
370}
371
372void Choreographer::signalRefreshRateCallbacks(nsecs_t vsyncPeriod) {
373 std::lock_guard<std::mutex> _l(gChoreographers.lock);
374 gChoreographers.mLastKnownVsync.store(vsyncPeriod);
375 for (auto c : gChoreographers.ptrs) {
376 c->scheduleLatestConfigRequest();
377 }
378}
379
380int64_t Choreographer::getStartTimeNanosForVsyncId(AVsyncId vsyncId) {
381 std::scoped_lock _l(gChoreographers.lock);
382 const auto iter = gChoreographers.startTimes.find(vsyncId);
383 if (iter == gChoreographers.startTimes.end()) {
384 ALOGW("Start time was not found for vsync id: %" PRId64, vsyncId);
385 return 0;
386 }
387 return iter->second;
388}
389
390} // namespace android