1 use std::iter::Iterator; 2 use std::time::Duration; 3 4 use num_rational::Ratio; 5 6 use crate::RgbaImage; 7 use crate::error::ImageResult; 8 9 /// An implementation dependent iterator, reading the frames as requested 10 pub struct Frames<'a> { 11 iterator: Box<dyn Iterator<Item = ImageResult<Frame>> + 'a> 12 } 13 14 impl<'a> Frames<'a> { 15 /// Creates a new `Frames` from an implementation specific iterator. 16 pub fn new(iterator: Box<dyn Iterator<Item = ImageResult<Frame>> + 'a>) -> Self { 17 Frames { iterator } 18 } 19 20 /// Steps through the iterator from the current frame until the end and pushes each frame into 21 /// a `Vec`. 22 /// If en error is encountered that error is returned instead. 23 /// 24 /// Note: This is equivalent to `Frames::collect::<ImageResult<Vec<Frame>>>()` 25 pub fn collect_frames(self) -> ImageResult<Vec<Frame>> { 26 self.collect() 27 } 28 } 29 30 impl<'a> Iterator for Frames<'a> { 31 type Item = ImageResult<Frame>; 32 fn next(&mut self) -> Option<ImageResult<Frame>> { 33 self.iterator.next() 34 } 35 } 36 37 /// A single animation frame 38 #[derive(Clone)] 39 pub struct Frame { 40 /// Delay between the frames in milliseconds 41 delay: Delay, 42 /// x offset 43 left: u32, 44 /// y offset 45 top: u32, 46 buffer: RgbaImage, 47 } 48 49 /// The delay of a frame relative to the previous one. 50 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd)] 51 pub struct Delay { 52 ratio: Ratio<u32>, 53 } 54 55 impl Frame { 56 /// Contructs a new frame without any delay. 57 pub fn new(buffer: RgbaImage) -> Frame { 58 Frame { 59 delay: Delay::from_ratio(Ratio::from_integer(0)), 60 left: 0, 61 top: 0, 62 buffer, 63 } 64 } 65 66 /// Contructs a new frame 67 pub fn from_parts(buffer: RgbaImage, left: u32, top: u32, delay: Delay) -> Frame { 68 Frame { 69 delay, 70 left, 71 top, 72 buffer, 73 } 74 } 75 76 /// Delay of this frame 77 pub fn delay(&self) -> Delay { 78 self.delay 79 } 80 81 /// Returns the image buffer 82 pub fn buffer(&self) -> &RgbaImage { 83 &self.buffer 84 } 85 86 /// Returns the image buffer 87 pub fn into_buffer(self) -> RgbaImage { 88 self.buffer 89 } 90 91 /// Returns the x offset 92 pub fn left(&self) -> u32 { 93 self.left 94 } 95 96 /// Returns the y offset 97 pub fn top(&self) -> u32 { 98 self.top 99 } 100 } 101 102 impl Delay { 103 /// Create a delay from a ratio of milliseconds. 104 /// 105 /// # Examples 106 /// 107 /// ``` 108 /// use image::Delay; 109 /// let delay_10ms = Delay::from_numer_denom_ms(10, 1); 110 /// ``` 111 pub fn from_numer_denom_ms(numerator: u32, denominator: u32) -> Self { 112 Delay { ratio: Ratio::new_raw(numerator, denominator) } 113 } 114 115 /// Convert from a duration, clamped between 0 and an implemented defined maximum. 116 /// 117 /// The maximum is *at least* `i32::MAX` milliseconds. It should be noted that the accuracy of 118 /// the result may be relative and very large delays have a coarse resolution. 119 /// 120 /// # Examples 121 /// 122 /// ``` 123 /// use std::time::Duration; 124 /// use image::Delay; 125 /// 126 /// let duration = Duration::from_millis(20); 127 /// let delay = Delay::from_saturating_duration(duration); 128 /// ``` 129 pub fn from_saturating_duration(duration: Duration) -> Self { 130 // A few notes: The largest number we can represent as a ratio is u32::MAX but we can 131 // sometimes represent much smaller numbers. 132 // 133 // We can represent duration as `millis+a/b` (where a < b, b > 0). 134 // We must thus bound b with `b·millis + (b-1) <= u32::MAX` or 135 // > `0 < b <= (u32::MAX + 1)/(millis + 1)` 136 // Corollary: millis <= u32::MAX 137 138 const MILLIS_BOUND: u128 = u32::max_value() as u128; 139 140 let millis = duration.as_millis().min(MILLIS_BOUND); 141 let submillis = (duration.as_nanos() % 1_000_000) as u32; 142 143 let max_b = if millis > 0 { 144 ((MILLIS_BOUND + 1)/(millis + 1)) as u32 145 } else { 146 MILLIS_BOUND as u32 147 }; 148 let millis = millis as u32; 149 150 let (a, b) = Self::closest_bounded_fraction(max_b, submillis, 1_000_000); 151 Self::from_numer_denom_ms(a + b*millis, b) 152 } 153 154 /// The numerator and denominator of the delay in milliseconds. 155 /// 156 /// This is guaranteed to be an exact conversion if the `Delay` was previously created with the 157 /// `from_numer_denom_ms` constructor. 158 pub fn numer_denom_ms(self) -> (u32, u32) { 159 (*self.ratio.numer(), *self.ratio.denom()) 160 } 161 162 pub(crate) fn from_ratio(ratio: Ratio<u32>) -> Self { 163 Delay { ratio } 164 } 165 166 pub(crate) fn into_ratio(self) -> Ratio<u32> { 167 self.ratio 168 } 169 170 /// Given some fraction, compute an approximation with denominator bounded. 171 /// 172 /// Note that `denom_bound` bounds nominator and denominator of all intermediate 173 /// approximations and the end result. 174 fn closest_bounded_fraction(denom_bound: u32, nom: u32, denom: u32) -> (u32, u32) { 175 use std::cmp::Ordering::{self, *}; 176 assert!(0 < denom); 177 assert!(0 < denom_bound); 178 assert!(nom < denom); 179 180 // Avoid a few type troubles. All intermediate results are bounded by `denom_bound` which 181 // is in turn bounded by u32::MAX. Representing with u64 allows multiplication of any two 182 // values without fears of overflow. 183 184 // Compare two fractions whose parts fit into a u32. 185 fn compare_fraction((an, ad): (u64, u64), (bn, bd): (u64, u64)) -> Ordering { 186 (an*bd).cmp(&(bn*ad)) 187 } 188 189 // Computes the nominator of the absolute difference between two such fractions. 190 fn abs_diff_nom((an, ad): (u64, u64), (bn, bd): (u64, u64)) -> u64 { 191 let c0 = an*bd; 192 let c1 = ad*bn; 193 194 let d0 = c0.max(c1); 195 let d1 = c0.min(c1); 196 d0 - d1 197 } 198 199 let exact = (u64::from(nom), u64::from(denom)); 200 // The lower bound fraction, numerator and denominator. 201 let mut lower = (0u64, 1u64); 202 // The upper bound fraction, numerator and denominator. 203 let mut upper = (1u64, 1u64); 204 // The closest approximation for now. 205 let mut guess = (u64::from(nom*2 > denom), 1u64); 206 207 // loop invariant: ad, bd <= denom_bound 208 // iterates the Farey sequence. 209 loop { 210 // Break if we are done. 211 if compare_fraction(guess, exact) == Equal { 212 break; 213 } 214 215 // Break if next Farey number is out-of-range. 216 if u64::from(denom_bound) - lower.1 < upper.1 { 217 break; 218 } 219 220 // Next Farey approximation n between a and b 221 let next = (lower.0 + upper.0, lower.1 + upper.1); 222 // if F < n then replace the upper bound, else replace lower. 223 if compare_fraction(exact, next) == Less { 224 upper = next; 225 } else { 226 lower = next; 227 } 228 229 // Now correct the closest guess. 230 // In other words, if |c - f| > |n - f| then replace it with the new guess. 231 // This favors the guess with smaller denominator on equality. 232 233 // |g - f| = |g_diff_nom|/(gd*fd); 234 let g_diff_nom = abs_diff_nom(guess, exact); 235 // |n - f| = |n_diff_nom|/(nd*fd); 236 let n_diff_nom = abs_diff_nom(next, exact); 237 238 // The difference |n - f| is smaller than |g - f| if either the integral part of the 239 // fraction |n_diff_nom|/nd is smaller than the one of |g_diff_nom|/gd or if they are 240 // the same but the fractional part is larger. 241 if match (n_diff_nom/next.1).cmp(&(g_diff_nom/guess.1)) { 242 Less => true, 243 Greater => false, 244 // Note that the nominator for the fractional part is smaller than its denominator 245 // which is smaller than u32 and can't overflow the multiplication with the other 246 // denominator, that is we can compare these fractions by multiplication with the 247 // respective other denominator. 248 Equal => compare_fraction((n_diff_nom%next.1, next.1), (g_diff_nom%guess.1, guess.1)) == Less, 249 } { 250 guess = next; 251 } 252 } 253 254 (guess.0 as u32, guess.1 as u32) 255 } 256 } 257 258 impl From<Delay> for Duration { 259 fn from(delay: Delay) -> Self { 260 let ratio = delay.into_ratio(); 261 let ms = ratio.to_integer(); 262 let rest = ratio.numer() % ratio.denom(); 263 let nanos = (u64::from(rest) * 1_000_000) / u64::from(*ratio.denom()); 264 Duration::from_millis(ms.into()) + Duration::from_nanos(nanos) 265 } 266 } 267 268 #[cfg(test)] 269 mod tests { 270 use super::{Delay, Duration, Ratio}; 271 272 #[test] 273 fn simple() { 274 let second = Delay::from_numer_denom_ms(1000, 1); 275 assert_eq!(Duration::from(second), Duration::from_secs(1)); 276 } 277 278 #[test] 279 fn fps_30() { 280 let thirtieth = Delay::from_numer_denom_ms(1000, 30); 281 let duration = Duration::from(thirtieth); 282 assert_eq!(duration.as_secs(), 0); 283 assert_eq!(duration.subsec_millis(), 33); 284 assert_eq!(duration.subsec_nanos(), 33_333_333); 285 } 286 287 #[test] 288 fn duration_outlier() { 289 let oob = Duration::from_secs(0xFFFF_FFFF); 290 let delay = Delay::from_saturating_duration(oob); 291 assert_eq!(delay.numer_denom_ms(), (0xFFFF_FFFF, 1)); 292 } 293 294 #[test] 295 fn duration_approx() { 296 let oob = Duration::from_millis(0xFFFF_FFFF) + Duration::from_micros(1); 297 let delay = Delay::from_saturating_duration(oob); 298 assert_eq!(delay.numer_denom_ms(), (0xFFFF_FFFF, 1)); 299 300 let inbounds = Duration::from_millis(0xFFFF_FFFF) - Duration::from_micros(1); 301 let delay = Delay::from_saturating_duration(inbounds); 302 assert_eq!(delay.numer_denom_ms(), (0xFFFF_FFFF, 1)); 303 304 let fine = Duration::from_millis(0xFFFF_FFFF/1000) + Duration::from_micros(0xFFFF_FFFF%1000); 305 let delay = Delay::from_saturating_duration(fine); 306 // Funnily, 0xFFFF_FFFF is divisble by 5, thus we compare with a `Ratio`. 307 assert_eq!(delay.into_ratio(), Ratio::new(0xFFFF_FFFF, 1000)); 308 } 309 310 #[test] 311 fn precise() { 312 // The ratio has only 32 bits in the numerator, too imprecise to get more than 11 digits 313 // correct. But it may be expressed as 1_000_000/3 instead. 314 let exceed = Duration::from_secs(333) + Duration::from_nanos(333_333_333); 315 let delay = Delay::from_saturating_duration(exceed); 316 assert_eq!(Duration::from(delay), exceed); 317 } 318 319 320 #[test] 321 fn small() { 322 // Not quite a delay of `1 ms`. 323 let delay = Delay::from_numer_denom_ms(1 << 16, (1 << 16) + 1); 324 let duration = Duration::from(delay); 325 assert_eq!(duration.as_millis(), 0); 326 // Not precisely the original but should be smaller than 0. 327 let delay = Delay::from_saturating_duration(duration); 328 assert_eq!(delay.into_ratio().to_integer(), 0); 329 } 330 } 331