1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! The pacer's source on Android: an `AChoreographer` on a looper thread of
//! the library's own.
/// `AChoreographer` works only on a thread with an `ALooper`, and Android
/// stores each thread's `AChoreographer` in a raw thread-local pointer with no
/// destroy API, so spawning a new thread per pacer would leak an
/// `AChoreographer`, its `ALooper`, and their file descriptors when each thread
/// exited. Instead, every pacer shares one library-owned looper thread started
/// on first use, independent of any caller's thread or UI looper. When no pacer
/// is active, the thread exits `ALooper_pollOnce` and parks on a Rust condvar
/// so it is not polling `ALooper` if the process exits.
///
/// A request registers the pacer's [`Vsyncs`] and signals an eventfd that the
/// thread's looper watches, and the watch's callback posts the frame callback.
///
/// `AChoreographer` can stop while the phone's display is off, even while a
/// Surface on another display, such as a car's, still shows the map. So each
/// request also arms a timerfd that the looper watches, which sends the frame
/// when the vsync is late. Once the timer sent a frame, it sends one every
/// [`TIMER_FRAME_INTERVAL`] that a frame is requested, until a vsync comes
/// first again. The pacer's throttle keeps the timer's frames within its
/// limit, as it does the vsyncs, so the source follows no limit of its own,
/// and a new one needs nothing from it.
#[cfg(target_os = "android")]
pub(crate) mod choreographer {
use core::cell::Cell;
use core::ffi::{c_int, c_long, c_void};
use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock, mpsc};
use std::thread::{self, ThreadId};
use std::time::Duration;
use mln_style::error::Error;
use parking_lot::{Condvar, Mutex};
use crate::frame_pacer::{Limit, VsyncSource, Vsyncs, catch_callback};
/// Longer than a vsync period at the lowest refresh rate that a phone
/// display runs at while it is on.
const VSYNC_TIMEOUT: Duration = Duration::from_millis(50);
const TIMER_FRAME_INTERVAL: Duration = Duration::from_millis(16);
#[repr(C)]
pub(crate) struct ALooper {
_opaque: [u8; 0],
}
#[repr(C)]
struct AChoreographer {
_opaque: [u8; 0],
}
type ALooperCallback = unsafe extern "C" fn(fd: c_int, events: c_int, data: *mut c_void) -> c_int;
type FrameCallback = unsafe extern "C" fn(frame_time_nanos: c_long, data: *mut c_void);
type FrameCallback64 = unsafe extern "C" fn(frame_time_nanos: i64, data: *mut c_void);
type PostFrameCallback64 = unsafe extern "C" fn(*mut AChoreographer, FrameCallback64, *mut c_void);
const ALOOPER_POLL_CALLBACK: c_int = -2;
const ALOOPER_POLL_ERROR: c_int = -4;
const ALOOPER_EVENT_INPUT: c_int = 1;
#[link(name = "android")]
unsafe extern "C" {
fn ALooper_prepare(opts: c_int) -> *mut ALooper;
fn ALooper_pollOnce(
timeout_millis: c_int,
out_fd: *mut c_int,
out_events: *mut c_int,
out_data: *mut *mut c_void,
) -> c_int;
fn ALooper_addFd(
looper: *mut ALooper,
fd: c_int,
ident: c_int,
events: c_int,
callback: Option<ALooperCallback>,
data: *mut c_void,
) -> c_int;
fn ALooper_removeFd(looper: *mut ALooper, fd: c_int) -> c_int;
fn AChoreographer_getInstance() -> *mut AChoreographer;
fn AChoreographer_postFrameCallback(
choreographer: *mut AChoreographer,
callback: FrameCallback,
data: *mut c_void,
);
}
/// API level 29 added `AChoreographer_postFrameCallback64()`. The older
/// `AChoreographer_postFrameCallback()` passes the frame time as a
/// `long`, which is 32 bits in a 32-bit process.
fn post_frame_callback64() -> Option<PostFrameCallback64> {
// SAFETY: a lookup of a NUL-terminated name.
let function = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"AChoreographer_postFrameCallback64".as_ptr()) };
// SAFETY: the NDK's function of that name has this signature.
(!function.is_null()).then(|| unsafe { core::mem::transmute::<*mut c_void, PostFrameCallback64>(function) })
}
/// The clock of a frame callback's frame time.
fn monotonic_now() -> Duration {
let mut now = libc::timespec { tv_sec: 0, tv_nsec: 0 };
// SAFETY: a local timespec.
unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &raw mut now) };
Duration::new(now.tv_sec as u64, now.tv_nsec as u32)
}
/// Arms `timer_fd` to expire once after `delay`, or disarms it for a zero
/// `delay`.
#[cfg_attr(
target_pointer_width = "64",
expect(
clippy::cast_lossless,
reason = "`c_long` takes the nanoseconds without loss only where it has 64 bits"
)
)]
fn arm_timer(timer_fd: c_int, delay: Duration) {
#[expect(clippy::as_underscore, reason = "`time_t` and `c_long` have 32 or 64 bits by target")]
let spec = libc::itimerspec {
it_interval: libc::timespec { tv_sec: 0, tv_nsec: 0 },
it_value: libc::timespec { tv_sec: delay.as_secs() as _, tv_nsec: delay.subsec_nanos() as _ },
};
// SAFETY: a local spec, and no old value to write.
unsafe { libc::timerfd_settime(timer_fd, 0, &raw const spec, core::ptr::null_mut()) };
}
/// Reads the 8-byte counter of an eventfd or a timerfd, and whether there
/// was one to read.
fn read_counter(fd: c_int) -> bool {
let mut count = 0_u64;
// SAFETY: reads at most the 8 bytes of a local.
let read = unsafe { libc::read(fd, (&raw mut count).cast(), size_of::<u64>()) };
read == size_of::<u64>() as isize
}
/// Whether the choreographer reports no vsyncs, as a test can make it.
fn choreographer_stopped() -> bool {
#[cfg(test)]
return tests::choreographer_stopped();
#[cfg(not(test))]
false
}
/// The shared looper thread, once it started.
static THREAD: Mutex<Option<Arc<PacerThread>>> = Mutex::new(None);
#[derive(Default)]
struct SharedState {
/// Number of live [`ChoreographerSource`]s using the thread.
active: usize,
/// Incremented whenever `active` drops to 0 so callbacks posted in an
/// earlier active period cannot satisfy a later period's requests.
epoch: u64,
/// Whether the looper thread is currently in its `ALooper_pollOnce`
/// loop rather than parked on `wake_cv`.
polling: bool,
/// Whether the looper thread stopped after an `ALOOPER_POLL_ERROR`.
failed: bool,
next_id: u64,
/// Pacers waiting for the next refresh, keyed by source ID.
waiting: BTreeMap<u64, Vsyncs>,
}
/// The process-wide looper thread shared by all Android frame pacers.
struct PacerThread {
id: OnceLock<ThreadId>,
event_fd: c_int,
state: Mutex<SharedState>,
/// Wakes the thread when `active` transitions from 0 to non-zero.
wake_cv: Condvar,
/// Notifies a thread dropping the last pacer once the looper thread has
/// left `ALooper_pollOnce` (or another pacer became active).
idle_cv: Condvar,
}
impl Drop for PacerThread {
fn drop(&mut self) {
// SAFETY: the thread's own eventfd, closed only if startup failed
// before the thread was stored in `THREAD`.
unsafe { libc::close(self.event_fd) };
}
}
impl PacerThread {
/// Returns the shared looper thread, starting it on first use.
fn get() -> Result<Arc<Self>, Error> {
let mut started = THREAD.lock();
if let Some(thread) = started.as_ref() {
return Ok(Arc::clone(thread));
}
// SAFETY: flags only.
let event_fd = unsafe { libc::eventfd(0, libc::EFD_CLOEXEC | libc::EFD_NONBLOCK) };
if event_fd < 0 {
return Err(Error::failed("the frame pacer could not create an eventfd"));
}
let thread = Arc::new(Self {
id: OnceLock::new(),
event_fd,
state: Mutex::new(SharedState::default()),
wake_cv: Condvar::new(),
idle_cv: Condvar::new(),
});
let (ready, readied) = mpsc::sync_channel(1);
let worker = Arc::clone(&thread);
let handle = thread::Builder::new()
.name("MLN frame pacer".into())
.spawn(move || run(&worker, &ready))
.map_err(|error| Error::failed(format!("the frame pacer could not start its thread: {error}")))?;
match readied.recv() {
Ok(Ok(())) => {
*started = Some(Arc::clone(&thread));
Ok(thread)
}
Ok(Err(error)) => {
let _ = handle.join();
Err(error)
}
Err(_) => {
let _ = handle.join();
Err(Error::failed("the frame pacer's thread stopped before starting its looper"))
}
}
}
fn is_current(&self) -> bool {
self.id.get().is_some_and(|&id| id == thread::current().id())
}
fn wake(&self) {
let one = 1_u64;
// A write that fails because the counter is full still leaves
// the looper a signal to read.
// SAFETY: writes the 8 bytes of a local.
while unsafe { libc::write(self.event_fd, (&raw const one).cast(), size_of::<u64>()) } < 0
&& std::io::Error::last_os_error().raw_os_error() == Some(libc::EINTR)
{}
}
}
/// State owned solely by the looper thread.
struct Looper {
looper: *mut ALooper,
choreographer: Cell<*mut AChoreographer>,
thread: Arc<PacerThread>,
timer_fd: c_int,
/// Whether any pacer waits for a frame that neither a vsync nor the
/// timer has sent.
requested: Cell<bool>,
/// Whether an `AChoreographer` frame callback is currently posted.
frame_posted: Cell<bool>,
/// The active-period `epoch` when the currently posted `AChoreographer`
/// callback was scheduled.
posted_epoch: Cell<u64>,
/// Whether the timer sent the last frame.
vsync_stopped: Cell<bool>,
last_frame_time: Cell<Option<Duration>>,
}
impl Drop for Looper {
fn drop(&mut self) {
// SAFETY: this thread's own looper and descriptors.
unsafe {
ALooper_removeFd(self.looper, self.thread.event_fd);
ALooper_removeFd(self.looper, self.timer_fd);
libc::close(self.timer_fd);
}
}
}
impl Looper {
/// Sends a frame at `time` to every waiting pacer. Runs on the looper's
/// thread. For native vsyncs (`expected_epoch = Some(epoch)`), checks
/// that the active-period epoch matches under the same lock that takes
/// `waiting`, returning `Err((current_epoch, has_waiting))` if the
/// callback predates the current active period.
fn send_frame(&self, time: Duration, expected_epoch: Option<u64>) -> Result<(), (u64, bool)> {
let waiters: Vec<Vsyncs> = {
let mut state = self.thread.state.lock();
if let Some(expected) = expected_epoch
&& state.epoch != expected
{
return Err((state.epoch, !state.waiting.is_empty()));
}
core::mem::take(&mut state.waiting).into_values().collect()
};
self.requested.set(false);
self.vsync_stopped.set(expected_epoch.is_none());
arm_timer(self.timer_fd, Duration::ZERO);
if waiters.is_empty() {
return Ok(());
}
// A vsync's time can come before the time of a timer frame
// sent just before it.
let time = self.last_frame_time.get().map_or(time, |last| time.max(last + Duration::from_nanos(1)));
self.last_frame_time.set(Some(time));
#[cfg(test)]
if expected_epoch.is_some() {
tests::record_vsync_frame();
}
// Each waiter's panic is caught alone, so one pacer's panic
// can't leave the other pacers, already taken from `waiting`,
// waiting for a refresh forever.
for vsyncs in waiters {
catch_callback((), || vsyncs.vsync(time));
}
Ok(())
}
fn post_frame(&self, epoch: u64, data: *mut c_void) {
self.frame_posted.set(true);
self.posted_epoch.set(epoch);
// SAFETY: this thread's choreographer, initialized before the
// looper polls, and `data` points to `self` for the thread's
// lifetime.
unsafe {
let choreographer = self.choreographer.get();
match post_frame_callback64() {
Some(post) => post(choreographer, on_frame64, data),
None => AChoreographer_postFrameCallback(choreographer, on_frame, data),
}
}
}
/// Asks for a frame. Runs on the looper's thread.
fn request_frame(&self, epoch: u64, data: *mut c_void) {
if self.requested.replace(true) {
return;
}
// A frame callback that is still posted serves this request (or, if
// it predates the current epoch, triggers a fresh post once it
// drains).
if !self.frame_posted.get() && !choreographer_stopped() {
self.post_frame(epoch, data);
}
let delay = if self.vsync_stopped.get() { TIMER_FRAME_INTERVAL } else { VSYNC_TIMEOUT };
arm_timer(self.timer_fd, delay);
}
fn run_frame(&self, time: Duration, data: *mut c_void) {
self.frame_posted.set(false);
if !self.requested.get() {
// A frame callback that was posted before the timer took
// over shows that vsyncs arrive again.
self.vsync_stopped.set(false);
return;
}
if let Err((current_epoch, has_waiting)) = self.send_frame(time, Some(self.posted_epoch.get())) {
// Discard a callback posted in an earlier active period; if a
// pacer is waiting in the new period, post a fresh callback
// while keeping `requested` and the fallback timer active.
self.vsync_stopped.set(false);
if has_waiting && !choreographer_stopped() {
self.post_frame(current_epoch, data);
} else {
self.requested.set(false);
arm_timer(self.timer_fd, Duration::ZERO);
}
}
}
}
unsafe extern "C" fn on_frame64(frame_time_nanos: i64, data: *mut c_void) {
catch_callback((), || {
// SAFETY: `data` is the `Looper` that posted this callback, live
// until the thread exits.
let looper = unsafe { &*data.cast::<Looper>() };
looper.run_frame(Duration::from_nanos(frame_time_nanos.max(0) as u64), data);
});
}
/// A 32-bit `long` carries only the low bits of the frame time, so the
/// high bits come from `CLOCK_MONOTONIC`, the frame time's clock, as the
/// NDK recommends.
unsafe extern "C" fn on_frame(frame_time_nanos: c_long, data: *mut c_void) {
catch_callback((), || {
#[cfg_attr(
target_pointer_width = "64",
expect(clippy::useless_conversion, reason = "a `long` is an `i64` in a 64-bit process")
)]
let mut time = i64::from(frame_time_nanos);
if size_of::<c_long>() < size_of::<i64>() {
const LOW_BITS: i64 = 0xffff_ffff;
let now = monotonic_now().as_nanos() as i64;
time = (now & !LOW_BITS) | (time & LOW_BITS);
if time > now {
time -= LOW_BITS + 1;
}
}
// SAFETY: `data` is the `Looper` that posted this callback, live
// until the thread exits.
let looper = unsafe { &*data.cast::<Looper>() };
looper.run_frame(Duration::from_nanos(time.max(0) as u64), data);
});
}
unsafe extern "C" fn on_signal(fd: c_int, _events: c_int, data: *mut c_void) -> c_int {
catch_callback(1, || {
// SAFETY: `data` is the `Looper` that registered this watch, live
// until the thread exits.
let looper = unsafe { &*data.cast::<Looper>() };
read_counter(fd);
let request_epoch = {
let state = looper.thread.state.lock();
(!state.waiting.is_empty()).then_some(state.epoch)
};
if let Some(epoch) = request_epoch {
looper.request_frame(epoch, data);
}
1
})
}
unsafe extern "C" fn on_timer(fd: c_int, _events: c_int, data: *mut c_void) -> c_int {
catch_callback(1, || {
// SAFETY: `data` is the `Looper` that registered this watch, live
// until the thread exits.
let looper = unsafe { &*data.cast::<Looper>() };
// A timer that a frame disarmed after it expired has nothing to
// read.
let expired = read_counter(fd);
if expired && looper.requested.get() {
let _ = looper.send_frame(monotonic_now(), None);
}
1
})
}
/// The shared looper thread's body.
fn run(thread: &Arc<PacerThread>, ready: &mpsc::SyncSender<Result<(), Error>>) {
let _ = thread.id.set(thread::current().id());
// SAFETY: prepares this thread's own looper.
let looper = unsafe { ALooper_prepare(0) };
if looper.is_null() {
let _ = ready.send(Err(Error::failed("the frame pacer could not prepare an ALooper")));
return;
}
// Create the timerfd and register both watches before obtaining the
// non-destroyable `AChoreographer`, so a failure here leaks none.
// SAFETY: flags only.
let timer_fd = unsafe { libc::timerfd_create(libc::CLOCK_MONOTONIC, libc::TFD_CLOEXEC | libc::TFD_NONBLOCK) };
if timer_fd < 0 {
let _ = ready.send(Err(Error::failed("the frame pacer could not create a timerfd")));
return;
}
// Heap-allocated so `data` stays at a fixed address for the thread's
// lifetime.
let looper_state = Box::new(Looper {
looper,
choreographer: Cell::new(core::ptr::null_mut()),
thread: Arc::clone(thread),
timer_fd,
requested: Cell::new(false),
frame_posted: Cell::new(false),
posted_epoch: Cell::new(0),
vsync_stopped: Cell::new(false),
last_frame_time: Cell::new(None),
});
let data = core::ptr::from_ref(&*looper_state).cast_mut().cast::<c_void>();
// SAFETY: this thread's looper, and `looper_state` stays alive at
// `data` until `Drop` removes the watches.
let added = unsafe {
ALooper_addFd(looper, thread.event_fd, ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT, Some(on_signal), data)
};
if added != 1 {
let _ = ready.send(Err(Error::failed("the frame pacer could not watch its eventfd")));
return;
}
// SAFETY: as above.
let added = unsafe {
ALooper_addFd(
looper,
looper_state.timer_fd,
ALOOPER_POLL_CALLBACK,
ALOOPER_EVENT_INPUT,
Some(on_timer),
data,
)
};
if added != 1 {
let _ = ready.send(Err(Error::failed("the frame pacer could not watch its timerfd")));
return;
}
// SAFETY: this thread has a looper.
let choreographer = unsafe { AChoreographer_getInstance() };
if choreographer.is_null() {
let _ = ready.send(Err(Error::failed("the frame pacer could not get an AChoreographer")));
return;
}
looper_state.choreographer.set(choreographer);
if ready.send(Ok(())).is_err() {
return;
}
loop {
{
let mut state = thread.state.lock();
state.polling = false;
thread.idle_cv.notify_all();
while state.active == 0 {
thread.wake_cv.wait(&mut state);
}
state.polling = true;
}
let mut poll_error = false;
while thread.state.lock().active > 0 {
// SAFETY: this thread's own looper, and no outputs.
let result = unsafe {
ALooper_pollOnce(-1, core::ptr::null_mut(), core::ptr::null_mut(), core::ptr::null_mut())
};
if result == ALOOPER_POLL_ERROR {
poll_error = true;
break;
}
}
looper_state.requested.set(false);
arm_timer(looper_state.timer_fd, Duration::ZERO);
if poll_error {
let mut state = thread.state.lock();
state.failed = true;
state.polling = false;
thread.idle_cv.notify_all();
break;
}
}
}
/// A pacer's handle to the shared Android choreographer thread.
pub(crate) struct ChoreographerSource {
thread: Arc<PacerThread>,
id: u64,
vsyncs: Vsyncs,
}
impl ChoreographerSource {
pub(crate) fn new(vsyncs: Vsyncs, _limit: Option<Limit>) -> Result<Self, Error> {
let thread = PacerThread::get()?;
let id = {
let mut state = thread.state.lock();
if state.failed {
return Err(Error::failed("the frame pacer's looper stopped with an error"));
}
state.active += 1;
state.next_id += 1;
let id = state.next_id;
thread.wake_cv.notify_all();
thread.idle_cv.notify_all();
id
};
Ok(Self { thread, id, vsyncs })
}
}
impl VsyncSource for ChoreographerSource {
fn schedule(&self) {
self.thread.state.lock().waiting.insert(self.id, self.vsyncs.clone());
self.thread.wake();
}
}
impl Drop for ChoreographerSource {
/// Stops polling once the last pacer drops, waiting for the looper
/// thread to park unless this runs on that thread itself (such as when
/// a pacer is dropped from its own refresh callback).
fn drop(&mut self) {
let mut state = self.thread.state.lock();
state.waiting.remove(&self.id);
state.active -= 1;
if state.active == 0 {
state.epoch = state.epoch.wrapping_add(1);
self.thread.wake();
if !self.thread.is_current() {
while state.polling && state.active == 0 {
self.thread.idle_cv.wait(&mut state);
}
}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use super::*;
use crate::frame_pacer::{FramePacer, RefreshWaiter};
static TEST_LOCK: Mutex<()> = Mutex::new(());
static CHOREOGRAPHER_STOPPED: AtomicBool = AtomicBool::new(false);
static VSYNC_FRAMES: AtomicUsize = AtomicUsize::new(0);
pub(super) fn choreographer_stopped() -> bool {
CHOREOGRAPHER_STOPPED.load(Ordering::SeqCst)
}
pub(super) fn record_vsync_frame() {
VSYNC_FRAMES.fetch_add(1, Ordering::SeqCst);
}
struct StopChoreographer;
impl StopChoreographer {
fn new() -> Self {
CHOREOGRAPHER_STOPPED.store(true, Ordering::SeqCst);
Self
}
}
impl Drop for StopChoreographer {
fn drop(&mut self) {
CHOREOGRAPHER_STOPPED.store(false, Ordering::SeqCst);
}
}
/// Expects the pacer to call a waiter back at each of a few requests,
/// from another thread than the calling thread, at increasing times,
/// and returns the callback thread's ID.
fn expect_refreshes(pacer: &FramePacer) -> ThreadId {
let caller = thread::current().id();
let (sender, refreshes) = mpsc::channel();
let waiter: Arc<dyn RefreshWaiter> = Arc::new(move |time| {
let _ = sender.send((thread::current().id(), time));
});
let mut last = Duration::ZERO;
let mut callback_thread = None;
for _ in 0..3 {
pacer.request(&waiter);
let (thread_id, time) = refreshes.recv().expect("the pacer calls back");
assert_ne!(thread_id, caller);
assert!(time > last);
last = time;
callback_thread = Some(thread_id);
}
callback_thread.unwrap()
}
#[test]
fn a_choreographer_calls_back_at_vsyncs_without_a_caller_looper() {
let _serial = TEST_LOCK.lock();
let before = VSYNC_FRAMES.load(Ordering::SeqCst);
let pacer = FramePacer::new(None).unwrap();
expect_refreshes(&pacer);
assert!(VSYNC_FRAMES.load(Ordering::SeqCst) > before, "expected native AChoreographer vsync callbacks");
}
#[test]
fn pacers_reuse_one_looper_thread() {
let _serial = TEST_LOCK.lock();
let first_thread = {
let pacer = FramePacer::new(None).unwrap();
expect_refreshes(&pacer)
};
let second_thread = {
let pacer = FramePacer::new(None).unwrap();
expect_refreshes(&pacer)
};
assert_eq!(first_thread, second_thread);
}
#[test]
fn a_blocked_calling_looper_does_not_delay_refreshes() {
let _serial = TEST_LOCK.lock();
// Preparing an ALooper on the calling thread and never polling it
// simulates a busy host UI thread: the pacer's own looper thread
// must still deliver vsyncs.
thread::spawn(|| {
// SAFETY: prepares this test thread's own looper.
let looper = unsafe { ALooper_prepare(0) };
assert!(!looper.is_null());
let pacer = FramePacer::new(None).unwrap();
expect_refreshes(&pacer);
})
.join()
.unwrap();
}
#[test]
fn the_timer_calls_back_while_the_choreographer_stops() {
let _serial = TEST_LOCK.lock();
let _stopped = StopChoreographer::new();
let before = VSYNC_FRAMES.load(Ordering::SeqCst);
let pacer = FramePacer::new(None).unwrap();
expect_refreshes(&pacer);
assert_eq!(VSYNC_FRAMES.load(Ordering::SeqCst), before);
}
#[test]
fn dropping_the_pacer_from_its_own_callback_does_not_deadlock() {
struct DropReporter(mpsc::Sender<ThreadId>);
impl Drop for DropReporter {
fn drop(&mut self) {
let _ = self.0.send(thread::current().id());
}
}
// Fields drop in declaration order: `source` drops first, then
// `reporter` sends the thread that ran `Drop` once
// `ChoreographerSource::drop` has returned.
struct Tracked {
source: ChoreographerSource,
_reporter: DropReporter,
}
impl VsyncSource for Tracked {
fn schedule(&self) {
self.source.schedule();
}
}
let _serial = TEST_LOCK.lock();
let (dropped_tx, dropped_rx) = mpsc::channel();
let (callback_tx, callback_rx) = mpsc::channel();
let pacer = FramePacer::with_source(None, |vsyncs, limit| {
Ok::<_, Error>(Tracked {
source: ChoreographerSource::new(vsyncs, limit)?,
_reporter: DropReporter(dropped_tx),
})
})
.unwrap();
// Move the only external `Arc` into `held` before requesting so
// the callback is guaranteed to drop the last external reference
// while `Vsyncs::vsync` holds the final `Arc` on the looper thread.
let held = Arc::new(Mutex::new(Some(pacer)));
let waiter: Arc<dyn RefreshWaiter> = Arc::new({
let held = Arc::clone(&held);
move |_| {
let _ = callback_tx.send(thread::current().id());
drop(held.lock().take());
}
});
held.lock().as_ref().unwrap().request(&waiter);
let callback_thread = callback_rx.recv().expect("the pacer calls back");
let drop_thread = dropped_rx.recv().expect("the source drops");
assert_eq!(drop_thread, callback_thread);
assert!(held.lock().is_none());
}
}
}