Skip to main content

clairlune_live/
lib.rs

1//! Clairlune's live wallpaper: a saved scene
2//! plays behind the desktop icons.
3//!
4//! [`Player`] keeps the frame between ticks with the incremental compositor
5//! and writes only the rectangles that changed into a 0RGB buffer, which the
6//! presenter copies to the screen as damage. The pixels come from the same
7//! compositor as the still PNG, with the same palette, so the first live
8//! frame (at the hero time) is the static wallpaper, except that on a GPU
9//! the particles sit at their own sub-cell positions ([`Player::set_smooth`])
10//! instead of the cell grid.
11
12use clairlune_render::clock::Clock;
13use clairlune_render::{IncrementalFrame, IndexedImage, PixelRect, ScenePackage};
14use clairlune_scene::Theme;
15use std::sync::{Arc, Mutex};
16use std::time::{Duration, Instant};
17
18pub mod cover;
19#[cfg(windows)]
20pub mod d3d11;
21#[cfg(windows)]
22pub mod desktop;
23pub mod dirty;
24pub mod gpu;
25#[cfg(target_os = "macos")]
26pub mod mac;
27#[cfg(target_os = "macos")]
28pub mod menu_bar;
29#[cfg(target_os = "macos")]
30pub mod surface;
31
32/// What a maximized or full-screen app pauses.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub enum CoverPolicy {
35    /// The monitor it covers.
36    #[default]
37    ThatMonitor,
38    /// Every monitor.
39    AllMonitors,
40    /// Nothing.
41    Off,
42}
43
44/// What one frame cost, for budgets and logs.
45#[derive(Clone, Copy, Debug, Default)]
46pub struct FrameStats {
47    /// Pixels uploaded or copied, over all monitors.
48    pub pixels: u64,
49    /// Rectangles uploaded or copied.
50    pub rects: usize,
51    /// Monitors paused because a window covers them.
52    pub covered: usize,
53    /// Paused everywhere: the session is locked or the displays are off.
54    pub away: bool,
55    /// Presents that waited over 50 ms for the swapchain (the compositor
56    /// holding frames back).
57    pub stalls: usize,
58    /// Time spent compositing, uploading and presenting.
59    pub busy: Duration,
60    /// Of which uploading, and drawing plus presenting.
61    pub upload: Duration,
62    pub present: Duration,
63}
64
65/// Shared full-scene compositor when one [`ScenePackage`] is spread across
66/// several monitors: composites once per tick instead of once per monitor.
67struct SharedSpread {
68    frame: IncrementalFrame,
69    /// `(t_ms, clock)` currently in `frame`.
70    at: Option<(u64, Clock)>,
71    /// Incremented whenever `frame` advances to a new instant.
72    seq: u64,
73    journey_top: Option<u32>,
74}
75
76enum FrameSource {
77    /// Whole-package player (one scene per monitor): composites directly.
78    Direct(IncrementalFrame),
79    /// One monitor's crop of a spread scene.
80    Shared {
81        shared: Arc<Mutex<SharedSpread>>,
82        own: IndexedImage,
83        /// Rectangles (in package coordinates) drawn onto `own` on this
84        /// monitor's last `advance`.
85        drawn: Vec<PixelRect>,
86        seen_seq: u64,
87        synced: bool,
88    },
89}
90
91/// Plays one saved scene, one frame at a time.
92pub struct Player {
93    pkg: Arc<ScenePackage>,
94    theme: Theme,
95    buddy: bool,
96    source: FrameSource,
97    /// Palette index to 0RGB.
98    colors: [u32; 256],
99    /// Scene time when playback started (the hero time, so the first frame
100    /// is the still), and when that was.
101    t0: u64,
102    started: Instant,
103    /// `Clock::Live` (particles on the cell grid) or `Clock::Smooth`.
104    clock: Clock,
105    /// The part of the frame this player shows (one monitor of a scene
106    /// spread over several); the whole frame otherwise.
107    view: PixelRect,
108}
109
110impl Player {
111    /// `None` if the scene has no such theme.
112    pub fn new(pkg: Arc<ScenePackage>, theme: Theme, buddy: bool) -> Option<Player> {
113        if pkg.width == 0 || pkg.height == 0 {
114            return None;
115        }
116        let frame = pkg.incremental(theme)?;
117        let colors = palette_colors(&pkg, theme)?;
118        let t0 = pkg.hero_ms(theme)?;
119        let view = PixelRect {
120            x: 0,
121            y: 0,
122            w: pkg.width,
123            h: pkg.height,
124        };
125        Some(Player {
126            pkg,
127            theme,
128            buddy,
129            source: FrameSource::Direct(frame),
130            colors,
131            t0,
132            started: Instant::now(),
133            clock: Clock::Live,
134            view,
135        })
136    }
137
138    /// A player showing only `view` of the scene's frame (span mode: each
139    /// monitor shows its part of one scene). Every method then works in the
140    /// view's own coordinates. `None` if the scene has no such theme or the
141    /// view isn't inside the frame.
142    pub fn new_view(
143        pkg: Arc<ScenePackage>,
144        theme: Theme,
145        buddy: bool,
146        view: PixelRect,
147    ) -> Option<Player> {
148        Self::build_view(pkg, theme, buddy, view, None)
149    }
150
151    fn build_view(
152        pkg: Arc<ScenePackage>,
153        theme: Theme,
154        buddy: bool,
155        view: PixelRect,
156        existing: Option<Arc<Mutex<SharedSpread>>>,
157    ) -> Option<Player> {
158        let inside =
159            |at: u32, len: u32, room: u32| at.checked_add(len).is_some_and(|end| end <= room);
160        if view.w == 0
161            || view.h == 0
162            || !inside(view.x, view.w, pkg.width)
163            || !inside(view.y, view.h, pkg.height)
164        {
165            return None;
166        }
167        let colors = palette_colors(&pkg, theme)?;
168        let t0 = pkg.hero_ms(theme)?;
169        let shared = match existing {
170            Some(s) => s,
171            None => {
172                let frame = pkg.incremental(theme)?;
173                let journey_top = pkg.journey_band_top(theme);
174                Arc::new(Mutex::new(SharedSpread {
175                    frame,
176                    at: None,
177                    seq: 0,
178                    journey_top,
179                }))
180            }
181        };
182        let (own, synced) = {
183            let guard = shared.lock().unwrap_or_else(|e| e.into_inner());
184            let mut own = IndexedImage::new(view.w, view.h);
185            copy_crop(guard.frame.image(), view, &whole_rect(view), &mut own);
186            (own, guard.at.is_none())
187        };
188        Some(Player {
189            pkg,
190            theme,
191            buddy,
192            source: FrameSource::Shared {
193                shared,
194                own,
195                drawn: Vec::new(),
196                seen_seq: 0,
197                synced,
198            },
199            colors,
200            t0,
201            started: Instant::now(),
202            clock: Clock::Live,
203            view,
204        })
205    }
206
207    /// Whether this player plays the same `(package, theme, buddy)` scene, so
208    /// another monitor can share its spread compositor via [`Player::with_view`].
209    pub fn shares_scene(&self, pkg: &Arc<ScenePackage>, theme: Theme, buddy: bool) -> bool {
210        Arc::ptr_eq(&self.pkg, pkg) && self.theme == theme && self.buddy == buddy
211    }
212
213    /// Particles at sub-cell positions (`Clock::Smooth`), for presenters on
214    /// a GPU: a higher frame rate then moves them smoothly. Off by default,
215    /// so the first frame is the still exactly; the CPU fallback keeps it
216    /// off.
217    pub fn set_smooth(&mut self, on: bool) {
218        self.clock = if on { Clock::Smooth } else { Clock::Live };
219    }
220
221    /// Another player of the same scene at the same moment, showing `view`
222    /// of it (one scene on several screens, each showing its part) and sharing
223    /// one full-scene compositor when spread. `None` if the view isn't inside
224    /// the frame.
225    pub fn with_view(&self, view: PixelRect) -> Option<Player> {
226        let existing = match &self.source {
227            FrameSource::Shared { shared, .. } => Some(shared.clone()),
228            FrameSource::Direct(_) => None,
229        };
230        let mut p = Self::build_view(self.pkg.clone(), self.theme, self.buddy, view, existing)?;
231        p.t0 = self.t0;
232        p.started = self.started;
233        p.clock = self.clock;
234        Some(p)
235    }
236
237    /// Whether the scene is a journey (its whole frame moves every tick).
238    pub fn is_journey(&self) -> bool {
239        self.pkg
240            .graph(self.theme)
241            .is_some_and(|g| g.journey.is_some())
242    }
243
244    /// The size of what this player shows.
245    pub fn size(&self) -> (u32, u32) {
246        (self.view.w, self.view.h)
247    }
248
249    /// The player's current frame (its view) as palette indices.
250    pub fn image(&self) -> &IndexedImage {
251        match &self.source {
252            FrameSource::Direct(frame) => frame.image(),
253            FrameSource::Shared { own, .. } => own,
254        }
255    }
256
257    /// Palette indices of `w` pixels of row `y` from column `x`, in the
258    /// view's coordinates.
259    pub fn index_row(&self, x: u32, y: u32, w: u32) -> &[u8] {
260        let img = self.image();
261        let a = y as usize * img.width as usize + x as usize;
262        &img.pixels[a..a + w as usize]
263    }
264
265    /// The palette as 0RGB, by index.
266    pub fn colors(&self) -> &[u32; 256] {
267        &self.colors
268    }
269
270    /// Scene time now: the hero time plus the time since playback started.
271    /// A pause only stops drawing; the next frame shows the time it is.
272    pub fn now_ms(&self) -> u64 {
273        self.t0 + self.started.elapsed().as_millis() as u64
274    }
275
276    /// Moves to `t_ms`; returns the rectangles that changed, in the view's
277    /// coordinates (changes outside the view are left out).
278    pub fn advance(&mut self, t_ms: u64) -> Vec<PixelRect> {
279        let v = self.view;
280        match &mut self.source {
281            FrameSource::Direct(frame) => self
282                .pkg
283                .advance(frame, self.theme, self.buddy, t_ms, self.clock)
284                .unwrap_or_default(),
285            FrameSource::Shared {
286                shared,
287                own,
288                drawn,
289                seen_seq,
290                synced,
291            } => {
292                let mut guard = shared.lock().unwrap_or_else(|e| e.into_inner());
293                let reuse = *seen_seq < guard.seq
294                    && guard.at.is_some_and(|(s_t, s_clock)| {
295                        s_clock == self.clock && t_ms.abs_diff(s_t) <= 4
296                    });
297                if !reuse {
298                    let _ = self.pkg.advance(
299                        &mut guard.frame,
300                        self.theme,
301                        self.buddy,
302                        t_ms,
303                        self.clock,
304                    );
305                    guard.at = Some((t_ms, self.clock));
306                    guard.seq = guard.seq.wrapping_add(1);
307                }
308                *seen_seq = guard.seq;
309                let now_drawn = guard.frame.drawn();
310                if !*synced {
311                    let all = whole_rect(v);
312                    copy_crop(guard.frame.image(), v, &all, own);
313                    drawn.clear();
314                    drawn.extend(now_drawn.iter().copied().filter(|r| overlaps(*r, v)));
315                    *synced = true;
316                    return vec![all];
317                }
318                let mut changed: Vec<PixelRect> = match guard.journey_top {
319                    Some(top) => {
320                        let top = top.min(self.pkg.height);
321                        let above = |r: &PixelRect| -> Option<PixelRect> {
322                            let y1 = (r.y + r.h).min(top);
323                            (r.y < y1).then(|| PixelRect { h: y1 - r.y, ..*r })
324                        };
325                        let mut list: Vec<PixelRect> = drawn
326                            .iter()
327                            .chain(now_drawn)
328                            .filter_map(above)
329                            .filter_map(|r| clip_to_view(r, v))
330                            .collect();
331                        if top < self.pkg.height {
332                            let band = PixelRect {
333                                x: 0,
334                                y: top,
335                                w: self.pkg.width,
336                                h: self.pkg.height - top,
337                            };
338                            if let Some(b) = clip_to_view(band, v) {
339                                list.push(b);
340                            }
341                        }
342                        list
343                    }
344                    None => drawn
345                        .iter()
346                        .chain(now_drawn)
347                        .filter_map(|&r| clip_to_view(r, v))
348                        .collect(),
349                };
350                changed.sort_unstable();
351                changed.dedup();
352                for r in &changed {
353                    copy_crop(guard.frame.image(), v, r, own);
354                }
355                drawn.clear();
356                drawn.extend(now_drawn.iter().copied().filter(|r| overlaps(*r, v)));
357                changed
358            }
359        }
360    }
361
362    /// Writes those rectangles (view coordinates) of the current frame into
363    /// a 0RGB buffer of the view's size.
364    pub fn write(&self, buf: &mut [u32], rects: &[PixelRect]) {
365        let w = self.view.w as usize;
366        debug_assert_eq!(buf.len(), w * self.view.h as usize);
367        for r in rects {
368            for y in r.y..r.y + r.h {
369                let a = y as usize * w + r.x as usize;
370                let row = self.index_row(r.x, y, r.w);
371                for (out, &i) in buf[a..a + r.w as usize].iter_mut().zip(row) {
372                    *out = self.colors[usize::from(i)];
373                }
374            }
375        }
376    }
377
378    /// One rectangle (view coordinates) of the current frame as 0RGB
379    /// pixels, row by row.
380    pub fn rect_pixels(&self, r: &PixelRect, out: &mut Vec<u32>) {
381        out.clear();
382        for y in r.y..r.y + r.h {
383            out.extend(
384                self.index_row(r.x, y, r.w)
385                    .iter()
386                    .map(|&i| self.colors[usize::from(i)]),
387            );
388        }
389    }
390
391    /// Writes the whole view.
392    pub fn write_all(&self, buf: &mut [u32]) {
393        let whole = PixelRect {
394            x: 0,
395            y: 0,
396            w: self.view.w,
397            h: self.view.h,
398        };
399        self.write(buf, &[whole]);
400    }
401}
402
403/// The highest frame rate for a journey: its land moves, so every frame is
404/// the whole screen, and Very smooth already scrolls evenly.
405pub const JOURNEY_MAX_FPS: u32 = 30;
406
407fn palette_colors(pkg: &ScenePackage, theme: Theme) -> Option<[u32; 256]> {
408    let mut colors = [0u32; 256];
409    for (i, c) in pkg.palette(theme)?.colors().iter().enumerate() {
410        colors[i] = (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b);
411    }
412    Some(colors)
413}
414
415fn whole_rect(view: PixelRect) -> PixelRect {
416    PixelRect {
417        x: 0,
418        y: 0,
419        w: view.w,
420        h: view.h,
421    }
422}
423
424fn overlaps(a: PixelRect, b: PixelRect) -> bool {
425    a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y
426}
427
428fn clip_to_view(r: PixelRect, v: PixelRect) -> Option<PixelRect> {
429    let x0 = r.x.max(v.x);
430    let y0 = r.y.max(v.y);
431    let x1 = (r.x + r.w).min(v.x + v.w);
432    let y1 = (r.y + r.h).min(v.y + v.h);
433    (x1 > x0 && y1 > y0).then(|| PixelRect {
434        x: x0 - v.x,
435        y: y0 - v.y,
436        w: x1 - x0,
437        h: y1 - y0,
438    })
439}
440
441/// Copies `rect` (in `view`'s local coordinates) from `src` into `dst`.
442fn copy_crop(src: &IndexedImage, view: PixelRect, rect: &PixelRect, dst: &mut IndexedImage) {
443    let sw = src.width as usize;
444    let dw = dst.width as usize;
445    for y in rect.y..rect.y + rect.h {
446        let sa = (view.y + y) as usize * sw + (view.x + rect.x) as usize;
447        let da = y as usize * dw + rect.x as usize;
448        dst.pixels[da..da + rect.w as usize].copy_from_slice(&src.pixels[sa..sa + rect.w as usize]);
449    }
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455    use clairlune_render::to_rgba;
456    use clairlune_scene::{Aspect, ContentContext, compose};
457
458    fn player() -> Player {
459        let r = compose(42, Aspect::from_size(320, 180), &ContentContext::default());
460        let pkg = Arc::new(ScenePackage::capture(&r, 320, 180).unwrap());
461        let theme = pkg.themes()[0];
462        Player::new(pkg, theme, true).unwrap()
463    }
464
465    fn rgb(buf: &[u32]) -> Vec<u8> {
466        buf.iter()
467            .flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255])
468            .collect()
469    }
470
471    #[test]
472    fn the_first_frame_is_the_still_and_updates_keep_the_buffer_exact() {
473        let mut p = player();
474        let (w, h) = p.size();
475        let mut buf = vec![0u32; (w * h) as usize];
476        let t0 = p.t0;
477        let rects = p.advance(t0);
478        p.write_all(&mut buf);
479        let _ = rects;
480        let (still, palette) = p.pkg.still(p.theme, true).unwrap();
481        assert_eq!(rgb(&buf), to_rgba(&still, palette));
482        // Then only the changed rects, as a presenter does.
483        for k in 1..40u64 {
484            let t = t0 + k * 83;
485            let rects = p.advance(t);
486            p.write(&mut buf, &rects);
487            let (full, palette) = p.pkg.frame(p.theme, true, t, Clock::Live).unwrap();
488            assert_eq!(rgb(&buf), to_rgba(&full, palette), "t {t}");
489        }
490    }
491
492    /// Span mode: a player showing part of a wide scene keeps a buffer of
493    /// just that part exact, from its own changed rects, like a whole-frame
494    /// player does.
495    #[test]
496    fn a_view_shows_its_part_of_the_frame_exactly() {
497        let (w, h) = (640, 180);
498        let r = compose(7, Aspect::from_size(w, h), &ContentContext::default());
499        let pkg = Arc::new(ScenePackage::capture(&r, w, h).unwrap());
500        let theme = pkg.themes()[0];
501        // The right half, as a second monitor of the same height.
502        let view = PixelRect {
503            x: 320,
504            y: 0,
505            w: 320,
506            h: 180,
507        };
508        let mut p = Player::new_view(pkg.clone(), theme, true, view).unwrap();
509        assert_eq!(p.size(), (320, 180));
510        let mut buf = vec![0u32; 320 * 180];
511        let t0 = p.t0;
512        p.advance(t0);
513        p.write_all(&mut buf);
514        let crop = |t: u64| -> Vec<u32> {
515            let (full, palette) = pkg.frame(theme, true, t, Clock::Live).unwrap();
516            let colors: Vec<u32> = palette
517                .colors()
518                .iter()
519                .map(|c| (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b))
520                .collect();
521            (0..180)
522                .flat_map(|y| (320..640).map(move |x| (x, y)))
523                .map(|(x, y)| colors[usize::from(full.pixels[y * 640 + x])])
524                .collect()
525        };
526        assert_eq!(buf, crop(t0));
527        for k in 1..40u64 {
528            let t = t0 + k * 83;
529            let rects = p.advance(t);
530            assert!(rects.iter().all(|r| r.x + r.w <= 320 && r.y + r.h <= 180));
531            p.write(&mut buf, &rects);
532            assert_eq!(buf, crop(t), "t {t}");
533        }
534        // A view outside the frame is refused.
535        let outside = PixelRect {
536            x: 400,
537            y: 0,
538            w: 320,
539            h: 180,
540        };
541        assert!(Player::new_view(pkg, theme, true, outside).is_none());
542    }
543
544    #[test]
545    fn shared_spread_views_stay_exact_even_when_one_monitor_pauses() {
546        let (w, h) = (640, 180);
547        for activity in ["warm_hands", "broom_journey"] {
548            let ctx = ContentContext {
549                enabled_activities: vec![activity.into()],
550                ..ContentContext::default()
551            };
552            let r = compose(11, Aspect::from_size(w, h), &ctx);
553            let pkg = Arc::new(ScenePackage::capture(&r, w, h).unwrap());
554            let theme = pkg.themes()[0];
555            let left_v = PixelRect {
556                x: 0,
557                y: 0,
558                w: 320,
559                h: 180,
560            };
561            let right_v = PixelRect {
562                x: 320,
563                y: 0,
564                w: 320,
565                h: 180,
566            };
567            let mut left = Player::new_view(pkg.clone(), theme, true, left_v).unwrap();
568            left.set_smooth(true);
569            let mut right = left.with_view(right_v).unwrap();
570            let mut buf_l = vec![0u32; 320 * 180];
571            let mut buf_r = vec![0u32; 320 * 180];
572            let t0 = left.t0;
573
574            let crop = |t: u64, x0: usize| -> Vec<u32> {
575                let (full, palette) = pkg.frame(theme, true, t, Clock::Smooth).unwrap();
576                let colors: Vec<u32> = palette
577                    .colors()
578                    .iter()
579                    .map(|c| (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b))
580                    .collect();
581                (0..180)
582                    .flat_map(|y| (x0..x0 + 320).map(move |x| (x, y)))
583                    .map(|(x, y)| colors[usize::from(full.pixels[y * 640 + x])])
584                    .collect()
585            };
586
587            left.advance(t0);
588            right.advance(t0);
589            left.write_all(&mut buf_l);
590            right.write_all(&mut buf_r);
591            assert_eq!(buf_l, crop(t0, 0), "{activity} hero left");
592            assert_eq!(buf_r, crop(t0, 320), "{activity} hero right");
593
594            for step in 1..=30u64 {
595                let t = t0 + step * 83;
596                let rl = left.advance(t);
597                left.write(&mut buf_l, &rl);
598                assert_eq!(buf_l, crop(t, 0), "{activity} step {step} left");
599                // Pause the right monitor for steps 8..22 while left keeps advancing,
600                // then uncover it and check incremental catch-up!
601                if !(8..22).contains(&step) {
602                    let rr = right.advance(t);
603                    right.write(&mut buf_r, &rr);
604                    assert_eq!(buf_r, crop(t, 320), "{activity} step {step} right");
605                }
606            }
607        }
608    }
609}