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