blob: 99bf6badeec77c660f908bfa2cc111196fd08c55 [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
Rachel Lee2248f522023-01-27 16:45:23 -0800104Choreographer::Choreographer(const sp<Looper>& looper, const sp<IBinder>& layerHandle)
105 : DisplayEventDispatcher(looper, gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp, {},
106 layerHandle),
Rachel Leeace701c2022-10-05 10:23:47 -0700107 mLooper(looper),
108 mThreadId(std::this_thread::get_id()) {
109 std::lock_guard<std::mutex> _l(gChoreographers.lock);
110 gChoreographers.ptrs.push_back(this);
111}
112
113Choreographer::~Choreographer() {
114 std::lock_guard<std::mutex> _l(gChoreographers.lock);
115 gChoreographers.ptrs.erase(std::remove_if(gChoreographers.ptrs.begin(),
116 gChoreographers.ptrs.end(),
117 [=](Choreographer* c) { return c == this; }),
118 gChoreographers.ptrs.end());
119 // Only poke DisplayManagerGlobal to unregister if we previously registered
120 // callbacks.
121 if (gChoreographers.ptrs.empty() && gChoreographers.registeredToDisplayManager) {
122 gChoreographers.registeredToDisplayManager = false;
123 JNIEnv* env = getJniEnv();
124 if (env == nullptr) {
125 ALOGW("JNI environment is unavailable, skipping choreographer cleanup");
126 return;
127 }
128 jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
129 gJni.displayManagerGlobal.getInstance);
130 if (dmg == nullptr) {
131 ALOGW("DMS is not initialized yet, skipping choreographer cleanup");
132 } else {
133 env->CallVoidMethod(dmg,
134 gJni.displayManagerGlobal
135 .unregisterNativeChoreographerForRefreshRateCallbacks);
136 env->DeleteLocalRef(dmg);
137 }
138 }
139}
140
141void Choreographer::postFrameCallbackDelayed(AChoreographer_frameCallback cb,
142 AChoreographer_frameCallback64 cb64,
143 AChoreographer_vsyncCallback vsyncCallback, void* data,
144 nsecs_t delay) {
145 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
146 FrameCallback callback{cb, cb64, vsyncCallback, data, now + delay};
147 {
148 std::lock_guard<std::mutex> _l{mLock};
149 mFrameCallbacks.push(callback);
150 }
151 if (callback.dueTime <= now) {
152 if (std::this_thread::get_id() != mThreadId) {
153 if (mLooper != nullptr) {
154 Message m{MSG_SCHEDULE_VSYNC};
155 mLooper->sendMessage(this, m);
156 } else {
157 scheduleVsync();
158 }
159 } else {
160 scheduleVsync();
161 }
162 } else {
163 if (mLooper != nullptr) {
164 Message m{MSG_SCHEDULE_CALLBACKS};
165 mLooper->sendMessageDelayed(delay, this, m);
166 } else {
167 scheduleCallbacks();
168 }
169 }
170}
171
172void Choreographer::registerRefreshRateCallback(AChoreographer_refreshRateCallback cb, void* data) {
173 std::lock_guard<std::mutex> _l{mLock};
174 for (const auto& callback : mRefreshRateCallbacks) {
175 // Don't re-add callbacks.
176 if (cb == callback.callback && data == callback.data) {
177 return;
178 }
179 }
180 mRefreshRateCallbacks.emplace_back(
181 RefreshRateCallback{.callback = cb, .data = data, .firstCallbackFired = false});
182 bool needsRegistration = false;
183 {
184 std::lock_guard<std::mutex> _l2(gChoreographers.lock);
185 needsRegistration = !gChoreographers.registeredToDisplayManager;
186 }
187 if (needsRegistration) {
188 JNIEnv* env = getJniEnv();
189 if (env == nullptr) {
190 ALOGW("JNI environment is unavailable, skipping registration");
191 return;
192 }
193 jobject dmg = env->CallStaticObjectMethod(gJni.displayManagerGlobal.clazz,
194 gJni.displayManagerGlobal.getInstance);
195 if (dmg == nullptr) {
196 ALOGW("DMS is not initialized yet: skipping registration");
197 return;
198 } else {
199 env->CallVoidMethod(dmg,
200 gJni.displayManagerGlobal
201 .registerNativeChoreographerForRefreshRateCallbacks,
202 reinterpret_cast<int64_t>(this));
203 env->DeleteLocalRef(dmg);
204 {
205 std::lock_guard<std::mutex> _l2(gChoreographers.lock);
206 gChoreographers.registeredToDisplayManager = true;
207 }
208 }
209 } else {
210 scheduleLatestConfigRequest();
211 }
212}
213
214void Choreographer::unregisterRefreshRateCallback(AChoreographer_refreshRateCallback cb,
215 void* data) {
216 std::lock_guard<std::mutex> _l{mLock};
217 mRefreshRateCallbacks.erase(std::remove_if(mRefreshRateCallbacks.begin(),
218 mRefreshRateCallbacks.end(),
219 [&](const RefreshRateCallback& callback) {
220 return cb == callback.callback &&
221 data == callback.data;
222 }),
223 mRefreshRateCallbacks.end());
224}
225
226void Choreographer::scheduleLatestConfigRequest() {
227 if (mLooper != nullptr) {
228 Message m{MSG_HANDLE_REFRESH_RATE_UPDATES};
229 mLooper->sendMessage(this, m);
230 } else {
231 // If the looper thread is detached from Choreographer, then refresh rate
232 // changes will be handled in AChoreographer_handlePendingEvents, so we
233 // need to wake up the looper thread by writing to the write-end of the
234 // socket the looper is listening on.
235 // Fortunately, these events are small so sending packets across the
236 // socket should be atomic across processes.
237 DisplayEventReceiver::Event event;
238 event.header =
239 DisplayEventReceiver::Event::Header{DisplayEventReceiver::DISPLAY_EVENT_NULL,
240 PhysicalDisplayId::fromPort(0), systemTime()};
241 injectEvent(event);
242 }
243}
244
245void Choreographer::scheduleCallbacks() {
246 const nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
247 nsecs_t dueTime;
248 {
249 std::lock_guard<std::mutex> _l{mLock};
250 // If there are no pending callbacks then don't schedule a vsync
251 if (mFrameCallbacks.empty()) {
252 return;
253 }
254 dueTime = mFrameCallbacks.top().dueTime;
255 }
256
257 if (dueTime <= now) {
258 ALOGV("choreographer %p ~ scheduling vsync", this);
259 scheduleVsync();
260 return;
261 }
262}
263
264void Choreographer::handleRefreshRateUpdates() {
265 std::vector<RefreshRateCallback> callbacks{};
266 const nsecs_t pendingPeriod = gChoreographers.mLastKnownVsync.load();
267 const nsecs_t lastPeriod = mLatestVsyncPeriod;
268 if (pendingPeriod > 0) {
269 mLatestVsyncPeriod = pendingPeriod;
270 }
271 {
272 std::lock_guard<std::mutex> _l{mLock};
273 for (auto& cb : mRefreshRateCallbacks) {
274 callbacks.push_back(cb);
275 cb.firstCallbackFired = true;
276 }
277 }
278
279 for (auto& cb : callbacks) {
280 if (!cb.firstCallbackFired || (pendingPeriod > 0 && pendingPeriod != lastPeriod)) {
281 cb.callback(pendingPeriod, cb.data);
282 }
283 }
284}
285
286void Choreographer::dispatchVsync(nsecs_t timestamp, PhysicalDisplayId, uint32_t,
287 VsyncEventData vsyncEventData) {
288 std::vector<FrameCallback> callbacks{};
289 {
290 std::lock_guard<std::mutex> _l{mLock};
291 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
292 while (!mFrameCallbacks.empty() && mFrameCallbacks.top().dueTime < now) {
293 callbacks.push_back(mFrameCallbacks.top());
294 mFrameCallbacks.pop();
295 }
296 }
297 mLastVsyncEventData = vsyncEventData;
298 for (const auto& cb : callbacks) {
299 if (cb.vsyncCallback != nullptr) {
300 const ChoreographerFrameCallbackDataImpl frameCallbackData =
301 createFrameCallbackData(timestamp);
302 registerStartTime();
303 mInCallback = true;
304 cb.vsyncCallback(reinterpret_cast<const AChoreographerFrameCallbackData*>(
305 &frameCallbackData),
306 cb.data);
307 mInCallback = false;
308 } else if (cb.callback64 != nullptr) {
309 cb.callback64(timestamp, cb.data);
310 } else if (cb.callback != nullptr) {
311 cb.callback(timestamp, cb.data);
312 }
313 }
314}
315
316void Choreographer::dispatchHotplug(nsecs_t, PhysicalDisplayId displayId, bool connected) {
317 ALOGV("choreographer %p ~ received hotplug event (displayId=%s, connected=%s), ignoring.", this,
318 to_string(displayId).c_str(), toString(connected));
319}
320
321void Choreographer::dispatchModeChanged(nsecs_t, PhysicalDisplayId, int32_t, nsecs_t) {
322 LOG_ALWAYS_FATAL("dispatchModeChanged was called but was never registered");
323}
324
325void Choreographer::dispatchFrameRateOverrides(nsecs_t, PhysicalDisplayId,
326 std::vector<FrameRateOverride>) {
327 LOG_ALWAYS_FATAL("dispatchFrameRateOverrides was called but was never registered");
328}
329
330void Choreographer::dispatchNullEvent(nsecs_t, PhysicalDisplayId) {
331 ALOGV("choreographer %p ~ received null event.", this);
332 handleRefreshRateUpdates();
333}
334
335void Choreographer::handleMessage(const Message& message) {
336 switch (message.what) {
337 case MSG_SCHEDULE_CALLBACKS:
338 scheduleCallbacks();
339 break;
340 case MSG_SCHEDULE_VSYNC:
341 scheduleVsync();
342 break;
343 case MSG_HANDLE_REFRESH_RATE_UPDATES:
344 handleRefreshRateUpdates();
345 break;
346 }
347}
348
349int64_t Choreographer::getFrameInterval() const {
350 return mLastVsyncEventData.frameInterval;
351}
352
353bool Choreographer::inCallback() const {
354 return mInCallback;
355}
356
357ChoreographerFrameCallbackDataImpl Choreographer::createFrameCallbackData(nsecs_t timestamp) const {
358 return {.frameTimeNanos = timestamp,
359 .vsyncEventData = mLastVsyncEventData,
360 .choreographer = this};
361}
362
363void Choreographer::registerStartTime() const {
364 std::scoped_lock _l(gChoreographers.lock);
365 for (VsyncEventData::FrameTimeline frameTimeline : mLastVsyncEventData.frameTimelines) {
366 while (gChoreographers.startTimes.size() >= kMaxStartTimes) {
367 gChoreographers.startTimes.erase(gChoreographers.startTimes.begin());
368 }
369 gChoreographers.startTimes[frameTimeline.vsyncId] = systemTime(SYSTEM_TIME_MONOTONIC);
370 }
371}
372
373void Choreographer::signalRefreshRateCallbacks(nsecs_t vsyncPeriod) {
374 std::lock_guard<std::mutex> _l(gChoreographers.lock);
375 gChoreographers.mLastKnownVsync.store(vsyncPeriod);
376 for (auto c : gChoreographers.ptrs) {
377 c->scheduleLatestConfigRequest();
378 }
379}
380
381int64_t Choreographer::getStartTimeNanosForVsyncId(AVsyncId vsyncId) {
382 std::scoped_lock _l(gChoreographers.lock);
383 const auto iter = gChoreographers.startTimes.find(vsyncId);
384 if (iter == gChoreographers.startTimes.end()) {
385 ALOGW("Start time was not found for vsync id: %" PRId64, vsyncId);
386 return 0;
387 }
388 return iter->second;
389}
390
391} // namespace android