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