Skip to main content

spoolframe_protocol/
previews.rs

1//! Frame previews for scrubbing: `Request::GetPreviews` and its
2//! reply.
3//!
4//! An item's previews are pictures of it at even intervals, packed row by
5//! row into sheets of `columns × rows` tiles. A sheet is an image like
6//! any other: read it on the artwork stream by its [`ArtworkId`],
7//! at [`crate::ArtworkSize::Original`], once for the item, and draw the
8//! part of it that [`Previews::tile`] names. A smaller size scales the
9//! whole sheet: scale the tile's rectangle by the image's width over
10//! `columns × tile_width`.
11
12use serde::{Deserialize, Serialize};
13use spoolframe_types::ArtworkId;
14
15/// An item's previews: what `GetPreviews` answers once they are made.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]
18pub struct Previews {
19    /// Tile `i` is the picture at about `i × interval` (the keyframe
20    /// at or just before it). `interval_ms` on the wire.
21    #[serde(rename = "interval_ms", with = "spoolframe_types::serde_time::millis")]
22    pub interval: std::time::Duration,
23    pub tile_width: u32,
24    pub tile_height: u32,
25    /// Tiles across a sheet.
26    pub columns: u32,
27    /// Tiles down a sheet.
28    pub rows: u32,
29    /// Tiles in all. The last sheet is filled only this far.
30    pub count: u32,
31    /// The sheets, in order: tiles `0..columns × rows` are on the first.
32    pub sheets: Vec<ArtworkId>,
33}
34
35/// Where the picture for a time is.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct PreviewTile {
38    /// Which tile, from 0.
39    pub index: u32,
40    /// Which sheet: an index into [`Previews::sheets`].
41    pub sheet: usize,
42    /// The tile's rectangle in the sheet, in pixels at its original size.
43    pub x: u32,
44    pub y: u32,
45    pub width: u32,
46    pub height: u32,
47}
48
49impl Previews {
50    /// The tile to show at `position`: the last one at or before it;
51    /// past the end, the last one. `None` only for previews with no
52    /// tiles, which the server does not send.
53    pub fn tile(&self, position: std::time::Duration) -> Option<PreviewTile> {
54        let per_sheet = self.columns.checked_mul(self.rows)?;
55        if self.count == 0 || per_sheet == 0 || self.interval.is_zero() {
56            return None;
57        }
58        let index = (position.as_millis() / self.interval.as_millis())
59            .min(u128::from(self.count - 1)) as u32;
60        let sheet = (index / per_sheet) as usize;
61        if sheet >= self.sheets.len() {
62            return None;
63        }
64        let at = index % per_sheet;
65        Some(PreviewTile {
66            index,
67            sheet,
68            x: (at % self.columns) * self.tile_width,
69            y: (at / self.columns) * self.tile_height,
70            width: self.tile_width,
71            height: self.tile_height,
72        })
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    //! Finding the tile for a time in an item's previews (P3-13).
79
80    use std::time::Duration;
81
82    use crate::{PreviewTile, Previews};
83    use spoolframe_types::ArtworkId;
84
85    /// A two-hour film at 10 s: 720 tiles of 320 × 134 on 8 sheets.
86    fn film() -> Previews {
87        Previews {
88            interval: std::time::Duration::from_millis(10_000),
89            tile_width: 320,
90            tile_height: 134,
91            columns: 10,
92            rows: 10,
93            count: 720,
94            sheets: (0..8)
95                .map(|n| format!("preview:abc/{n}").parse::<ArtworkId>().unwrap())
96                .collect(),
97        }
98    }
99
100    #[test]
101    fn the_tile_for_1_23_40_is_on_its_sheet_by_row_and_column() {
102        // 1:23:40 is 5020 s: tile 502, the 3rd of sheet 5, in its first row.
103        assert_eq!(
104            film().tile(Duration::from_millis(5_020_000)),
105            Some(PreviewTile {
106                index: 502,
107                sheet: 5,
108                x: 2 * 320,
109                y: 0,
110                width: 320,
111                height: 134,
112            })
113        );
114        // 37 s past it: still tile 505's span; tile 505 is the 6th, row 0.
115        let tile = film().tile(Duration::from_millis(5_057_000)).unwrap();
116        assert_eq!((tile.index, tile.x, tile.y), (505, 5 * 320, 0));
117        // Tile 579: sheet 5, row 7, column 9.
118        let tile = film().tile(Duration::from_millis(5_799_999)).unwrap();
119        assert_eq!(
120            (tile.index, tile.sheet, tile.x, tile.y),
121            (579, 5, 9 * 320, 7 * 134)
122        );
123    }
124
125    #[test]
126    fn a_time_between_tiles_shows_the_one_before() {
127        assert_eq!(film().tile(Duration::from_millis(0)).unwrap().index, 0);
128        assert_eq!(film().tile(Duration::from_millis(9_999)).unwrap().index, 0);
129        assert_eq!(film().tile(Duration::from_millis(10_000)).unwrap().index, 1);
130    }
131
132    #[test]
133    fn past_the_end_is_the_last_tile() {
134        let tile = film().tile(Duration::from_millis(10 * 3_600_000)).unwrap();
135        assert_eq!((tile.index, tile.sheet), (719, 7));
136        assert_eq!((tile.x, tile.y), (9 * 320, 134));
137    }
138
139    #[test]
140    fn previews_without_tiles_have_none() {
141        let empty = Previews {
142            count: 0,
143            sheets: vec![],
144            ..film()
145        };
146        assert_eq!(empty.tile(Duration::from_millis(0)), None);
147    }
148
149    #[test]
150    fn a_grid_that_is_not_square_is_read_by_its_columns() {
151        // 4 across, 3 down: 12 a sheet.
152        let previews = Previews {
153            columns: 4,
154            rows: 3,
155            count: 20,
156            sheets: film().sheets[..2].to_vec(),
157            ..film()
158        };
159        let tile = previews.tile(Duration::from_millis(70_000)).unwrap();
160        assert_eq!((tile.sheet, tile.x, tile.y), (0, 3 * 320, 134));
161        let tile = previews.tile(Duration::from_millis(130_000)).unwrap();
162        assert_eq!((tile.index, tile.sheet, tile.x, tile.y), (13, 1, 320, 0));
163    }
164}