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