Skip to main content

clairlune_live/
lib.rs

1//! Clairlune's live wallpaper (PLAN.md sections 2 and 5.3): 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;
16use std::time::{Duration, Instant};
17
18#[cfg(windows)]
19pub mod d3d11;
20#[cfg(windows)]
21pub mod desktop;
22pub mod gpu;
23#[cfg(target_os = "linux")]
24pub mod linux;
25#[cfg(target_os = "macos")]
26pub mod mac;
27#[cfg(target_os = "macos")]
28pub mod surface;
29
30/// What a maximized or full-screen app pauses.
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
32pub enum CoverPolicy {
33    /// The monitor it covers.
34    #[default]
35    ThatMonitor,
36    /// Every monitor.
37    AllMonitors,
38    /// Nothing.
39    Off,
40}
41
42/// What one frame cost, for budgets and logs.
43#[derive(Clone, Copy, Debug, Default)]
44pub struct FrameStats {
45    /// Pixels uploaded or copied, over all monitors.
46    pub pixels: u64,
47    /// Rectangles uploaded or copied.
48    pub rects: usize,
49    /// Monitors paused because a window covers them.
50    pub covered: usize,
51    /// Paused everywhere: the session is locked or the displays are off.
52    pub away: bool,
53    /// Presents that waited over 50 ms for the swapchain (the compositor
54    /// holding frames back).
55    pub stalls: usize,
56    /// Time spent compositing, uploading and presenting.
57    pub busy: Duration,
58    /// Of which uploading, and drawing plus presenting.
59    pub upload: Duration,
60    pub present: Duration,
61}
62
63/// Plays one saved scene, one frame at a time.
64pub struct Player {
65    pkg: Arc<ScenePackage>,
66    theme: Theme,
67    buddy: bool,
68    frame: IncrementalFrame,
69    /// Palette index to 0RGB.
70    colors: [u32; 256],
71    /// Scene time when playback started (the hero time, so the first frame
72    /// is the still), and when that was.
73    t0: u64,
74    started: Instant,
75    /// `Clock::Live` (particles on the cell grid) or `Clock::Smooth`.
76    clock: Clock,
77    /// The part of the frame this player shows (one monitor of a scene
78    /// spread over several); the whole frame otherwise.
79    view: PixelRect,
80}
81
82impl Player {
83    /// `None` if the scene has no such theme.
84    pub fn new(pkg: Arc<ScenePackage>, theme: Theme, buddy: bool) -> Option<Player> {
85        let view = PixelRect {
86            x: 0,
87            y: 0,
88            w: pkg.width,
89            h: pkg.height,
90        };
91        Self::new_view(pkg, theme, buddy, view)
92    }
93
94    /// A player showing only `view` of the scene's frame (span mode: each
95    /// monitor shows its part of one scene). Every method then works in the
96    /// view's own coordinates. `None` if the scene has no such theme or the
97    /// view isn't inside the frame.
98    pub fn new_view(
99        pkg: Arc<ScenePackage>,
100        theme: Theme,
101        buddy: bool,
102        view: PixelRect,
103    ) -> Option<Player> {
104        let inside =
105            |at: u32, len: u32, room: u32| at.checked_add(len).is_some_and(|end| end <= room);
106        if view.w == 0
107            || view.h == 0
108            || !inside(view.x, view.w, pkg.width)
109            || !inside(view.y, view.h, pkg.height)
110        {
111            return None;
112        }
113        let frame = pkg.incremental(theme)?;
114        let mut colors = [0u32; 256];
115        for (i, c) in pkg.palette(theme)?.colors().iter().enumerate() {
116            colors[i] = (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b);
117        }
118        let t0 = pkg.hero_ms(theme)?;
119        Some(Player {
120            pkg,
121            theme,
122            buddy,
123            frame,
124            colors,
125            t0,
126            started: Instant::now(),
127            clock: Clock::Live,
128            view,
129        })
130    }
131
132    /// Particles at sub-cell positions (`Clock::Smooth`), for presenters on
133    /// a GPU: a higher frame rate then moves them smoothly. Off by default,
134    /// so the first frame is the still exactly; the CPU fallback keeps it
135    /// off (PLAN.md section 4.4).
136    pub fn set_smooth(&mut self, on: bool) {
137        self.clock = if on { Clock::Smooth } else { Clock::Live };
138    }
139
140    /// Another player of the same scene at the same moment, showing `view`
141    /// of it (one scene on several screens, each showing its part). `None`
142    /// if the view isn't inside the frame.
143    pub fn with_view(&self, view: PixelRect) -> Option<Player> {
144        let mut p = Player::new_view(self.pkg.clone(), self.theme, self.buddy, view)?;
145        p.t0 = self.t0;
146        p.started = self.started;
147        p.clock = self.clock;
148        Some(p)
149    }
150
151    /// Whether the scene is a journey (its whole frame moves every tick).
152    pub fn is_journey(&self) -> bool {
153        self.pkg
154            .graph(self.theme)
155            .is_some_and(|g| g.journey.is_some())
156    }
157
158    /// The size of what this player shows.
159    pub fn size(&self) -> (u32, u32) {
160        (self.view.w, self.view.h)
161    }
162
163    /// The whole current frame as palette indices (not just the view).
164    pub fn image(&self) -> &IndexedImage {
165        self.frame.image()
166    }
167
168    /// Palette indices of `w` pixels of row `y` from column `x`, in the
169    /// view's coordinates.
170    pub fn index_row(&self, x: u32, y: u32, w: u32) -> &[u8] {
171        let img = self.frame.image();
172        let a = (self.view.y + y) as usize * img.width as usize + (self.view.x + x) as usize;
173        &img.pixels[a..a + w as usize]
174    }
175
176    /// The palette as 0RGB, by index.
177    pub fn colors(&self) -> &[u32; 256] {
178        &self.colors
179    }
180
181    /// Scene time now: the hero time plus the time since playback started.
182    /// A pause only stops drawing; the next frame shows the time it is.
183    pub fn now_ms(&self) -> u64 {
184        self.t0 + self.started.elapsed().as_millis() as u64
185    }
186
187    /// Moves to `t_ms`; returns the rectangles that changed, in the view's
188    /// coordinates (changes outside the view are left out).
189    pub fn advance(&mut self, t_ms: u64) -> Vec<PixelRect> {
190        let rects = self
191            .pkg
192            .advance(&mut self.frame, self.theme, self.buddy, t_ms, self.clock)
193            .unwrap_or_default();
194        let v = self.view;
195        if (v.x, v.y, v.w, v.h) == (0, 0, self.pkg.width, self.pkg.height) {
196            return rects;
197        }
198        rects
199            .iter()
200            .filter_map(|r| {
201                let x0 = r.x.max(v.x);
202                let y0 = r.y.max(v.y);
203                let x1 = (r.x + r.w).min(v.x + v.w);
204                let y1 = (r.y + r.h).min(v.y + v.h);
205                (x1 > x0 && y1 > y0).then(|| PixelRect {
206                    x: x0 - v.x,
207                    y: y0 - v.y,
208                    w: x1 - x0,
209                    h: y1 - y0,
210                })
211            })
212            .collect()
213    }
214
215    /// Writes those rectangles (view coordinates) of the current frame into
216    /// a 0RGB buffer of the view's size.
217    pub fn write(&self, buf: &mut [u32], rects: &[PixelRect]) {
218        let w = self.view.w as usize;
219        debug_assert_eq!(buf.len(), w * self.view.h as usize);
220        for r in rects {
221            for y in r.y..r.y + r.h {
222                let a = y as usize * w + r.x as usize;
223                let row = self.index_row(r.x, y, r.w);
224                for (out, &i) in buf[a..a + r.w as usize].iter_mut().zip(row) {
225                    *out = self.colors[usize::from(i)];
226                }
227            }
228        }
229    }
230
231    /// One rectangle (view coordinates) of the current frame as 0RGB
232    /// pixels, row by row.
233    pub fn rect_pixels(&self, r: &PixelRect, out: &mut Vec<u32>) {
234        out.clear();
235        for y in r.y..r.y + r.h {
236            out.extend(
237                self.index_row(r.x, y, r.w)
238                    .iter()
239                    .map(|&i| self.colors[usize::from(i)]),
240            );
241        }
242    }
243
244    /// Writes the whole view.
245    pub fn write_all(&self, buf: &mut [u32]) {
246        let whole = PixelRect {
247            x: 0,
248            y: 0,
249            w: self.view.w,
250            h: self.view.h,
251        };
252        self.write(buf, &[whole]);
253    }
254}
255
256/// The highest frame rate for a journey: its land moves, so every frame is
257/// the whole screen, and Very smooth already scrolls evenly.
258pub const JOURNEY_MAX_FPS: u32 = 30;
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263    use clairlune_render::to_rgba;
264    use clairlune_scene::{Aspect, ContentContext, compose};
265
266    fn player() -> Player {
267        let r = compose(42, Aspect::from_size(320, 180), &ContentContext::default());
268        let pkg = Arc::new(ScenePackage::capture(&r, 320, 180).unwrap());
269        let theme = pkg.themes()[0];
270        Player::new(pkg, theme, true).unwrap()
271    }
272
273    fn rgb(buf: &[u32]) -> Vec<u8> {
274        buf.iter()
275            .flat_map(|p| [(p >> 16) as u8, (p >> 8) as u8, *p as u8, 255])
276            .collect()
277    }
278
279    #[test]
280    fn the_first_frame_is_the_still_and_updates_keep_the_buffer_exact() {
281        let mut p = player();
282        let (w, h) = p.size();
283        let mut buf = vec![0u32; (w * h) as usize];
284        let t0 = p.t0;
285        let rects = p.advance(t0);
286        p.write_all(&mut buf);
287        let _ = rects;
288        let (still, palette) = p.pkg.still(p.theme, true).unwrap();
289        assert_eq!(rgb(&buf), to_rgba(&still, palette));
290        // Then only the changed rects, as a presenter does.
291        for k in 1..40u64 {
292            let t = t0 + k * 83;
293            let rects = p.advance(t);
294            p.write(&mut buf, &rects);
295            let (full, palette) = p.pkg.frame(p.theme, true, t, Clock::Live).unwrap();
296            assert_eq!(rgb(&buf), to_rgba(&full, palette), "t {t}");
297        }
298    }
299
300    /// Span mode: a player showing part of a wide scene keeps a buffer of
301    /// just that part exact, from its own changed rects, like a whole-frame
302    /// player does.
303    #[test]
304    fn a_view_shows_its_part_of_the_frame_exactly() {
305        let (w, h) = (640, 180);
306        let r = compose(7, Aspect::from_size(w, h), &ContentContext::default());
307        let pkg = Arc::new(ScenePackage::capture(&r, w, h).unwrap());
308        let theme = pkg.themes()[0];
309        // The right half, as a second monitor of the same height.
310        let view = PixelRect {
311            x: 320,
312            y: 0,
313            w: 320,
314            h: 180,
315        };
316        let mut p = Player::new_view(pkg.clone(), theme, true, view).unwrap();
317        assert_eq!(p.size(), (320, 180));
318        let mut buf = vec![0u32; 320 * 180];
319        let t0 = p.t0;
320        p.advance(t0);
321        p.write_all(&mut buf);
322        let crop = |t: u64| -> Vec<u32> {
323            let (full, palette) = pkg.frame(theme, true, t, Clock::Live).unwrap();
324            let colors: Vec<u32> = palette
325                .colors()
326                .iter()
327                .map(|c| (u32::from(c.r) << 16) | (u32::from(c.g) << 8) | u32::from(c.b))
328                .collect();
329            (0..180)
330                .flat_map(|y| (320..640).map(move |x| (x, y)))
331                .map(|(x, y)| colors[usize::from(full.pixels[y * 640 + x])])
332                .collect()
333        };
334        assert_eq!(buf, crop(t0));
335        for k in 1..40u64 {
336            let t = t0 + k * 83;
337            let rects = p.advance(t);
338            assert!(rects.iter().all(|r| r.x + r.w <= 320 && r.y + r.h <= 180));
339            p.write(&mut buf, &rects);
340            assert_eq!(buf, crop(t), "t {t}");
341        }
342        // A view outside the frame is refused.
343        let outside = PixelRect {
344            x: 400,
345            y: 0,
346            w: 320,
347            h: 180,
348        };
349        assert!(Player::new_view(pkg, theme, true, outside).is_none());
350    }
351}