| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | #![allow(clippy::chunks_exact_to_as_chunks)] |
| 16 | |
| 17 | use std::path::{Path, PathBuf}; |
| 18 | |
| 19 | |
| 20 | const DIR: &str = "/edith-gen"; |
| 21 | |
| 22 | |
| 23 | const MILLI: f64 = 1000.0; |
| 24 | |
| 25 | |
| 26 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 27 | pub enum Kind { |
| 28 | |
| 29 | Solid { rgb: u32 }, |
| 30 | |
| 31 | Gradient { a: u32, b: u32, angle: u16 }, |
| 32 | |
| 33 | |
| 34 | Countdown { from: u16, milli_fps: u32 }, |
| 35 | |
| 36 | Bars, |
| 37 | |
| 38 | Adjust, |
| 39 | |
| 40 | Shape(Shape), |
| 41 | } |
| 42 | |
| 43 | |
| 44 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 45 | pub enum Form { |
| 46 | |
| 47 | Rectangle, |
| 48 | Ellipse, |
| 49 | |
| 50 | Line, |
| 51 | |
| 52 | Arrow, |
| 53 | } |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 59 | pub struct Shape { |
| 60 | pub form: Form, |
| 61 | pub fill: Option<u32>, |
| 62 | pub stroke: Option<u32>, |
| 63 | |
| 64 | pub width: u16, |
| 65 | |
| 66 | pub radius: u16, |
| 67 | } |
| 68 | |
| 69 | impl Form { |
| 70 | |
| 71 | pub const ALL: [Form; 4] = [Form::Rectangle, Form::Ellipse, Form::Line, Form::Arrow]; |
| 72 | |
| 73 | pub fn name(self) -> &'static str { |
| 74 | match self { |
| 75 | Form::Rectangle => "rectangle", |
| 76 | Form::Ellipse => "ellipse", |
| 77 | Form::Line => "line", |
| 78 | Form::Arrow => "arrow", |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | pub fn title(self) -> &'static str { |
| 83 | match self { |
| 84 | Form::Rectangle => "Rectangle", |
| 85 | Form::Ellipse => "Ellipse", |
| 86 | Form::Line => "Line", |
| 87 | Form::Arrow => "Arrow", |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | |
| 92 | pub fn fills(self) -> bool { |
| 93 | matches!(self, Form::Rectangle | Form::Ellipse) |
| 94 | } |
| 95 | |
| 96 | fn by_name(name: &str) -> Option<Self> { |
| 97 | Self::ALL.into_iter().find(|f| f.name() == name) |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | impl Shape { |
| 102 | |
| 103 | pub fn of(form: Form) -> Self { |
| 104 | match form { |
| 105 | Form::Rectangle | Form::Ellipse => Self { form, fill: Some(0x2a6df4), stroke: None, width: 0, radius: 0 }, |
| 106 | Form::Line => Self { form, fill: None, stroke: Some(0xffffff), width: 12, radius: 0 }, |
| 107 | Form::Arrow => Self { form, fill: None, stroke: Some(0xff3b30), width: 14, radius: 0 }, |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | |
| 112 | |
| 113 | fn rgba(&self, w: usize, h: usize) -> Vec<u8> { |
| 114 | let mut out = vec![0u8; w * h * 4]; |
| 115 | let (fw, fh) = (w as f32, h as f32); |
| 116 | let sw = f32::from(self.width); |
| 117 | let stroke = self.stroke.filter(|_| self.width > 0).map(split); |
| 118 | let fill = self.fill.filter(|_| self.form.fills()).map(split); |
| 119 | |
| 120 | let base = stroke.or(fill).unwrap_or([0, 0, 0]); |
| 121 | let (cx, cy) = (fw / 2.0, fh / 2.0); |
| 122 | |
| 123 | let pad = sw * 0.5 + 1.0; |
| 124 | let head_len = (sw * 4.5).max(10.0).min(fw * 0.45); |
| 125 | let head_half = (sw * 2.4).max(6.0).min(fh * 0.45); |
| 126 | let tip = (fw - 1.0, cy); |
| 127 | let neck = (fw - 1.0 - head_len, cy); |
| 128 | let shaft_end = (neck.0 + head_len * 0.25, cy); |
| 129 | let tri = [tip, (neck.0, cy - head_half), (neck.0, cy + head_half)]; |
| 130 | let r_max = fw.min(fh) / 2.0; |
| 131 | let radius = f32::from(self.radius).min(r_max); |
| 132 | for y in 0..h { |
| 133 | for x in 0..w { |
| 134 | let (px, py) = (x as f32 + 0.5, y as f32 + 0.5); |
| 135 | |
| 136 | let d = match self.form { |
| 137 | Form::Rectangle => { |
| 138 | let (qx, qy) = ((px - cx).abs() - (fw / 2.0 - radius), (py - cy).abs() - (fh / 2.0 - radius)); |
| 139 | qx.max(qy).min(0.0) + qx.max(0.0).hypot(qy.max(0.0)) - radius |
| 140 | } |
| 141 | Form::Ellipse => { |
| 142 | let (rx, ry) = (fw / 2.0, fh / 2.0); |
| 143 | let (ex, ey) = ((px - cx) / rx, (py - cy) / ry); |
| 144 | let k0 = ex.hypot(ey); |
| 145 | let k1 = ((ex / rx).hypot(ey / ry)).max(1e-9); |
| 146 | k0 * (k0 - 1.0) / k1 |
| 147 | } |
| 148 | Form::Line => seg((px, py), (pad, cy), (fw - pad, cy)) - sw / 2.0, |
| 149 | Form::Arrow => { |
| 150 | let shaft = seg((px, py), (pad, cy), (shaft_end.0, cy)) - sw / 2.0; |
| 151 | shaft.min(tri_dist((px, py), tri)) |
| 152 | } |
| 153 | }; |
| 154 | let outside = !self.form.fills(); |
| 155 | |
| 156 | let outer = (0.5 - d).clamp(0.0, 1.0); |
| 157 | let (alpha, rgb) = if outside { |
| 158 | (outer, stroke.unwrap_or(base)) |
| 159 | } else { |
| 160 | let band = (0.5 + sw - (-d)).clamp(0.0, 1.0); |
| 161 | match (fill, stroke) { |
| 162 | (Some(f), Some(s)) => (outer, mix3(f, s, band)), |
| 163 | (Some(f), None) => (outer, f), |
| 164 | (None, Some(s)) => (outer * band, s), |
| 165 | (None, None) => (0.0, base), |
| 166 | } |
| 167 | }; |
| 168 | let o = &mut out[(y * w + x) * 4..][..4]; |
| 169 | o[..3].copy_from_slice(&rgb); |
| 170 | o[3] = (alpha * 255.0).round() as u8; |
| 171 | } |
| 172 | } |
| 173 | out |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn mix3(a: [u8; 3], b: [u8; 3], t: f32) -> [u8; 3] { |
| 178 | let m = |a: u8, b: u8| (f32::from(a) + (f32::from(b) - f32::from(a)) * t).round() as u8; |
| 179 | [m(a[0], b[0]), m(a[1], b[1]), m(a[2], b[2])] |
| 180 | } |
| 181 | |
| 182 | |
| 183 | fn seg(p: (f32, f32), a: (f32, f32), b: (f32, f32)) -> f32 { |
| 184 | let (pa, ba) = ((p.0 - a.0, p.1 - a.1), (b.0 - a.0, b.1 - a.1)); |
| 185 | let t = ((pa.0 * ba.0 + pa.1 * ba.1) / (ba.0 * ba.0 + ba.1 * ba.1).max(1e-9)).clamp(0.0, 1.0); |
| 186 | (pa.0 - ba.0 * t).hypot(pa.1 - ba.1 * t) |
| 187 | } |
| 188 | |
| 189 | |
| 190 | fn tri_dist(p: (f32, f32), t: [(f32, f32); 3]) -> f32 { |
| 191 | let d = (0..3).map(|i| seg(p, t[i], t[(i + 1) % 3])).fold(f32::MAX, f32::min); |
| 192 | let side = |a: (f32, f32), b: (f32, f32)| (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0); |
| 193 | let (s0, s1, s2) = (side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])); |
| 194 | let inside = (s0 >= 0.0 && s1 >= 0.0 && s2 >= 0.0) || (s0 <= 0.0 && s1 <= 0.0 && s2 <= 0.0); |
| 195 | if inside { -d } else { d } |
| 196 | } |
| 197 | |
| 198 | |
| 199 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 200 | pub struct Gen { |
| 201 | pub kind: Kind, |
| 202 | pub width: u32, |
| 203 | pub height: u32, |
| 204 | } |
| 205 | |
| 206 | |
| 207 | pub const KINDS: [&str; 9] = ["solid", "gradient", "countdown", "bars", "adjust", "rectangle", "ellipse", "line", "arrow"]; |
| 208 | |
| 209 | impl Kind { |
| 210 | |
| 211 | pub fn name(self) -> &'static str { |
| 212 | match self { |
| 213 | Kind::Solid { .. } => "solid", |
| 214 | Kind::Gradient { .. } => "gradient", |
| 215 | Kind::Countdown { .. } => "countdown", |
| 216 | Kind::Bars => "bars", |
| 217 | Kind::Adjust => "adjust", |
| 218 | Kind::Shape(s) => s.form.name(), |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | |
| 223 | pub fn title(self) -> &'static str { |
| 224 | match self { |
| 225 | Kind::Solid { .. } => "Solid colour", |
| 226 | Kind::Gradient { .. } => "Gradient", |
| 227 | Kind::Countdown { .. } => "Countdown", |
| 228 | Kind::Bars => "Colour bars", |
| 229 | Kind::Adjust => "Adjustment layer", |
| 230 | Kind::Shape(s) => s.form.title(), |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | impl Gen { |
| 236 | pub fn new(kind: Kind, width: u32, height: u32) -> Self { |
| 237 | Self { kind, width: width.clamp(16, 7680), height: height.clamp(16, 7680) } |
| 238 | } |
| 239 | |
| 240 | |
| 241 | pub fn named(name: &str, width: u32, height: u32, fps: f64) -> Option<Self> { |
| 242 | let kind = match name { |
| 243 | "solid" => Kind::Solid { rgb: 0x2a6df4 }, |
| 244 | "gradient" => Kind::Gradient { a: 0xff7a18, b: 0x3a1c71, angle: 90 }, |
| 245 | "countdown" => Kind::Countdown { from: 5, milli_fps: (fps * MILLI).round() as u32 }, |
| 246 | "bars" => Kind::Bars, |
| 247 | "adjust" => Kind::Adjust, |
| 248 | other => Kind::Shape(Shape::of(Form::by_name(other)?)), |
| 249 | }; |
| 250 | Some(Self::new(kind, width, height)) |
| 251 | } |
| 252 | |
| 253 | |
| 254 | pub fn animated(&self) -> bool { |
| 255 | matches!(self.kind, Kind::Countdown { .. }) |
| 256 | } |
| 257 | |
| 258 | |
| 259 | pub fn has_alpha(&self) -> bool { |
| 260 | matches!(self.kind, Kind::Shape(_)) |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | pub fn default_scale(&self) -> Option<f32> { |
| 266 | self.has_alpha().then_some(0.4) |
| 267 | } |
| 268 | |
| 269 | |
| 270 | pub fn alpha(&self) -> Option<Vec<u8>> { |
| 271 | let Kind::Shape(s) = self.kind else { return None }; |
| 272 | Some(s.rgba(self.width as usize, self.height as usize).chunks_exact(4).map(|p| p[3]).collect()) |
| 273 | } |
| 274 | |
| 275 | |
| 276 | pub fn is_adjust(&self) -> bool { |
| 277 | self.kind == Kind::Adjust |
| 278 | } |
| 279 | |
| 280 | |
| 281 | pub fn path(&self) -> PathBuf { |
| 282 | let (w, h) = (self.width, self.height); |
| 283 | let spec = match self.kind { |
| 284 | Kind::Solid { rgb } => format!("solid-{rgb:06x}-{w}x{h}"), |
| 285 | Kind::Gradient { a, b, angle } => format!("gradient-{a:06x}-{b:06x}-{angle}-{w}x{h}"), |
| 286 | Kind::Countdown { from, milli_fps } => format!("countdown-{from}-{milli_fps}-{w}x{h}"), |
| 287 | Kind::Bars => format!("bars-{w}x{h}"), |
| 288 | Kind::Adjust => format!("adjust-{w}x{h}"), |
| 289 | Kind::Shape(s) => { |
| 290 | let paint = |c: Option<u32>| c.map_or("none".to_string(), |c| format!("{c:06x}")); |
| 291 | format!("{}-{}-{}-{}-{}-{w}x{h}", s.form.name(), paint(s.fill), paint(s.stroke), s.width, s.radius) |
| 292 | } |
| 293 | }; |
| 294 | PathBuf::from(format!("{DIR}/{spec}.gen")) |
| 295 | } |
| 296 | |
| 297 | |
| 298 | pub fn parse(path: &Path) -> Option<Self> { |
| 299 | if path.parent()? != Path::new(DIR) || path.extension()? != "gen" { |
| 300 | return None; |
| 301 | } |
| 302 | let stem = path.file_stem()?.to_str()?; |
| 303 | let f: Vec<&str> = stem.split('-').collect(); |
| 304 | let hex = |s: &str| u32::from_str_radix(s, 16).ok().filter(|v| *v <= 0xff_ffff && s.len() == 6); |
| 305 | let (size, kind) = match f.as_slice() { |
| 306 | ["solid", c, size] => (size, Kind::Solid { rgb: hex(c)? }), |
| 307 | ["gradient", a, b, angle, size] => { |
| 308 | (size, Kind::Gradient { a: hex(a)?, b: hex(b)?, angle: angle.parse::<u16>().ok().filter(|a| *a < 360)? }) |
| 309 | } |
| 310 | ["countdown", from, fps, size] => ( |
| 311 | size, |
| 312 | Kind::Countdown { from: from.parse().ok().filter(|f| (1..=3600).contains(f))?, milli_fps: fps.parse().ok().filter(|f| *f > 0)? }, |
| 313 | ), |
| 314 | ["bars", size] => (size, Kind::Bars), |
| 315 | ["adjust", size] => (size, Kind::Adjust), |
| 316 | [form, fill, stroke, width, radius, size] => { |
| 317 | let paint = |s: &str| if s == "none" { Some(None) } else { hex(s).map(Some) }; |
| 318 | let shape = Shape { |
| 319 | form: Form::by_name(form)?, |
| 320 | fill: paint(fill)?, |
| 321 | stroke: paint(stroke)?, |
| 322 | width: width.parse().ok().filter(|v| *v <= 400)?, |
| 323 | radius: radius.parse().ok().filter(|v| *v <= 2000)?, |
| 324 | }; |
| 325 | (size, Kind::Shape(shape)) |
| 326 | } |
| 327 | _ => return None, |
| 328 | }; |
| 329 | let (w, h) = size.split_once('x')?; |
| 330 | let (width, height): (u32, u32) = (w.parse().ok()?, h.parse().ok()?); |
| 331 | ((16..=7680).contains(&width) && (16..=7680).contains(&height)).then_some(Self { kind, width, height }) |
| 332 | } |
| 333 | |
| 334 | |
| 335 | pub fn rgb(&self, frame: u32) -> Vec<u8> { |
| 336 | let (w, h) = (self.width as usize, self.height as usize); |
| 337 | let mut out = vec![0u8; w * h * 3]; |
| 338 | match self.kind { |
| 339 | Kind::Solid { rgb } => { |
| 340 | let c = split(rgb); |
| 341 | out.chunks_exact_mut(3).for_each(|p| p.copy_from_slice(&c)); |
| 342 | } |
| 343 | Kind::Gradient { a, b, angle } => { |
| 344 | let (ca, cb) = (split(a), split(b)); |
| 345 | let rad = f32::from(angle).to_radians(); |
| 346 | let (dx, dy) = (rad.cos(), rad.sin()); |
| 347 | |
| 348 | let span = (w as f32 * dx).abs() + (h as f32 * dy).abs(); |
| 349 | let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); |
| 350 | for y in 0..h { |
| 351 | for x in 0..w { |
| 352 | let p = ((x as f32 + 0.5 - cx) * dx + (y as f32 + 0.5 - cy) * dy) / span.max(1.0); |
| 353 | let t = (0.5 + p).clamp(0.0, 1.0); |
| 354 | let px = &mut out[(y * w + x) * 3..][..3]; |
| 355 | for k in 0..3 { |
| 356 | px[k] = (f32::from(ca[k]) + (f32::from(cb[k]) - f32::from(ca[k])) * t).round() as u8; |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | Kind::Bars => { |
| 362 | |
| 363 | const BARS: [[u8; 3]; 7] = [ |
| 364 | [191, 191, 191], |
| 365 | [191, 191, 0], |
| 366 | [0, 191, 191], |
| 367 | [0, 191, 0], |
| 368 | [191, 0, 191], |
| 369 | [191, 0, 0], |
| 370 | [0, 0, 191], |
| 371 | ]; |
| 372 | for y in 0..h { |
| 373 | for x in 0..w { |
| 374 | out[(y * w + x) * 3..][..3].copy_from_slice(&BARS[x * 7 / w]); |
| 375 | } |
| 376 | } |
| 377 | } |
| 378 | Kind::Countdown { from, milli_fps } => self.countdown(&mut out, from, milli_fps, frame), |
| 379 | Kind::Adjust => out.fill(128), |
| 380 | Kind::Shape(s) => { |
| 381 | let rgba = s.rgba(w, h); |
| 382 | for (p, q) in out.chunks_exact_mut(3).zip(rgba.chunks_exact(4)) { |
| 383 | p.copy_from_slice(&q[..3]); |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | out |
| 388 | } |
| 389 | |
| 390 | |
| 391 | |
| 392 | fn countdown(&self, out: &mut [u8], from: u16, milli_fps: u32, frame: u32) { |
| 393 | let (w, h) = (self.width as usize, self.height as usize); |
| 394 | let t = f64::from(frame) / (f64::from(milli_fps) / MILLI); |
| 395 | let whole = t.floor(); |
| 396 | let left = (f64::from(from) - whole).max(0.0) as u32; |
| 397 | |
| 398 | let sweep = if f64::from(from) - whole <= 0.0 { 0.0 } else { (t - whole) as f32 }; |
| 399 | let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0); |
| 400 | let radius = h as f32 * 0.38; |
| 401 | let ring = (h as f32 * 0.008).max(2.0); |
| 402 | for y in 0..h { |
| 403 | for x in 0..w { |
| 404 | let (dx, dy) = (x as f32 + 0.5 - cx, y as f32 + 0.5 - cy); |
| 405 | let d = (dx * dx + dy * dy).sqrt(); |
| 406 | let mut v = 32u8; |
| 407 | if d <= radius { |
| 408 | |
| 409 | let a = (dx.atan2(-dy) / std::f32::consts::TAU).rem_euclid(1.0); |
| 410 | if a <= sweep { |
| 411 | v = 72; |
| 412 | } |
| 413 | } |
| 414 | if (d - radius).abs() <= ring { |
| 415 | v = 235; |
| 416 | } |
| 417 | out[(y * w + x) * 3..][..3].fill(v); |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | let mut bgra = vec![255u8; w * h * 4]; |
| 422 | for (px, rgb) in bgra.chunks_exact_mut(4).zip(out.chunks_exact(3)) { |
| 423 | px[0] = rgb[2]; |
| 424 | px[1] = rgb[1]; |
| 425 | px[2] = rgb[0]; |
| 426 | } |
| 427 | let style = crate::text::TextStyle { |
| 428 | size: crate::text::SIZE_RANGE.1, |
| 429 | boxed: false, |
| 430 | place: crate::text::Place::Centre, |
| 431 | outline: crate::text::Outline::Thin, |
| 432 | ..Default::default() |
| 433 | }; |
| 434 | crate::text::draw_text(&mut bgra, self.width, self.height, &style, &[left.to_string()]); |
| 435 | for (px, rgb) in bgra.chunks_exact(4).zip(out.chunks_exact_mut(3)) { |
| 436 | rgb[0] = px[2]; |
| 437 | rgb[1] = px[1]; |
| 438 | rgb[2] = px[0]; |
| 439 | } |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | fn split(rgb: u32) -> [u8; 3] { |
| 444 | [(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8] |
| 445 | } |
| 446 | |
| 447 | |
| 448 | pub fn is_generated(path: &Path) -> bool { |
| 449 | Gen::parse(path).is_some() |
| 450 | } |
| 451 | |
| 452 | |
| 453 | pub fn is_adjust(path: &Path) -> bool { |
| 454 | Gen::parse(path).is_some_and(|g| g.is_adjust()) |
| 455 | } |
| 456 | |
| 457 | |
| 458 | pub fn title(path: &Path) -> Option<&'static str> { |
| 459 | Gen::parse(path).map(|g| g.kind.title()) |
| 460 | } |
| 461 | |
| 462 | |
| 463 | |
| 464 | pub fn tone_title(path: &Path) -> Option<String> { |
| 465 | let stem = path.file_name()?.to_str()?.strip_prefix("tone-")?.strip_suffix(".wav")?; |
| 466 | let (hz, rest) = stem.split_once("hz-")?; |
| 467 | let (db, _secs) = rest.split_once("dbfs-")?; |
| 468 | let hz: u32 = hz.parse().ok()?; |
| 469 | let db: i32 = db.parse().ok()?; |
| 470 | let freq = if hz >= 1000 { format!("{} kHz", f64::from(hz) / 1000.) } else { format!("{hz} Hz") }; |
| 471 | let level = if db < 0 { format!("\u{2212}{} dB", -db) } else { format!("{db} dB") }; |
| 472 | Some(format!("Tone {freq} \u{00b7} {level}")) |
| 473 | } |
| 474 | |
| 475 | |
| 476 | |
| 477 | |
| 478 | |
| 479 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 480 | pub struct Tone { |
| 481 | |
| 482 | pub hz: u32, |
| 483 | |
| 484 | pub dbfs: i32, |
| 485 | } |
| 486 | |
| 487 | |
| 488 | pub const TONE_RATE: u32 = 48_000; |
| 489 | |
| 490 | pub const TONE_SECS: u32 = 10; |
| 491 | |
| 492 | impl Tone { |
| 493 | |
| 494 | pub const DEFAULT: Tone = Tone { hz: 1000, dbfs: -20 }; |
| 495 | |
| 496 | |
| 497 | pub fn new(hz: u32, dbfs: i32) -> Self { |
| 498 | Self { hz: hz.clamp(20, 20_000), dbfs: dbfs.clamp(-60, -3) } |
| 499 | } |
| 500 | |
| 501 | |
| 502 | pub fn file_name(&self, secs: u32) -> String { |
| 503 | format!("tone-{}hz-{}dbfs-{secs}s.wav", self.hz, self.dbfs) |
| 504 | } |
| 505 | |
| 506 | |
| 507 | |
| 508 | pub fn dir() -> Option<std::path::PathBuf> { |
| 509 | Some(Self::dir_in(&crate::templates::data_home()?)) |
| 510 | } |
| 511 | |
| 512 | |
| 513 | pub fn dir_in(data: &std::path::Path) -> std::path::PathBuf { |
| 514 | data.join("edith").join("tones") |
| 515 | } |
| 516 | |
| 517 | |
| 518 | pub fn wav(&self, secs: u32) -> Vec<u8> { |
| 519 | let n = u64::from(secs) * u64::from(TONE_RATE); |
| 520 | let data_len = (n * 2) as u32; |
| 521 | let mut out = Vec::with_capacity(44 + data_len as usize); |
| 522 | out.extend_from_slice(b"RIFF"); |
| 523 | out.extend_from_slice(&(36 + data_len).to_le_bytes()); |
| 524 | out.extend_from_slice(b"WAVEfmt "); |
| 525 | out.extend_from_slice(&16u32.to_le_bytes()); |
| 526 | out.extend_from_slice(&1u16.to_le_bytes()); |
| 527 | out.extend_from_slice(&1u16.to_le_bytes()); |
| 528 | out.extend_from_slice(&TONE_RATE.to_le_bytes()); |
| 529 | out.extend_from_slice(&(TONE_RATE * 2).to_le_bytes()); |
| 530 | out.extend_from_slice(&2u16.to_le_bytes()); |
| 531 | out.extend_from_slice(&16u16.to_le_bytes()); |
| 532 | out.extend_from_slice(b"data"); |
| 533 | out.extend_from_slice(&data_len.to_le_bytes()); |
| 534 | let peak = 10f64.powf(f64::from(self.dbfs) / 20.0) * std::f64::consts::SQRT_2; |
| 535 | let step = std::f64::consts::TAU * f64::from(self.hz) / f64::from(TONE_RATE); |
| 536 | for i in 0..n { |
| 537 | let v = peak * (step * i as f64).sin(); |
| 538 | out.extend_from_slice(&((v * 32767.0).round() as i16).to_le_bytes()); |
| 539 | } |
| 540 | out |
| 541 | } |
| 542 | |
| 543 | |
| 544 | |
| 545 | pub fn write(&self, dir: &Path, secs: u32) -> crate::Result<PathBuf> { |
| 546 | let path = dir.join(self.file_name(secs)); |
| 547 | if path.is_file() { |
| 548 | return Ok(path); |
| 549 | } |
| 550 | std::fs::create_dir_all(dir).map_err(|e| format!("cannot make {}: {e}", dir.display()))?; |
| 551 | crate::edith::write_atomic(&path, &self.wav(secs))?; |
| 552 | Ok(path) |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | #[cfg(test)] |
| 557 | mod tests { |
| 558 | use super::*; |
| 559 | |
| 560 | #[test] |
| 561 | fn a_generator_survives_its_own_spelling() { |
| 562 | for g in [ |
| 563 | Gen::new(Kind::Solid { rgb: 0x123456 }, 1920, 1080), |
| 564 | Gen::new(Kind::Gradient { a: 0xff0000, b: 0x0000ff, angle: 45 }, 640, 360), |
| 565 | Gen::new(Kind::Countdown { from: 10, milli_fps: 29_970 }, 1280, 720), |
| 566 | Gen::new(Kind::Bars, 320, 240), |
| 567 | Gen::new(Kind::Adjust, 1920, 1080), |
| 568 | Gen::new(Kind::Shape(Shape { form: Form::Rectangle, fill: Some(0x112233), stroke: Some(0xffffff), width: 8, radius: 40 }), 1920, 1080), |
| 569 | Gen::new(Kind::Shape(Shape { form: Form::Ellipse, fill: None, stroke: Some(0xff0000), width: 3, radius: 0 }), 640, 360), |
| 570 | Gen::new(Kind::Shape(Shape::of(Form::Line)), 640, 360), |
| 571 | Gen::new(Kind::Shape(Shape::of(Form::Arrow)), 640, 360), |
| 572 | ] { |
| 573 | assert_eq!(Gen::parse(&g.path()), Some(g), "{:?}", g.path()); |
| 574 | } |
| 575 | for bad in ["/edith-gen/solid-12345-1920x1080.gen", "/edith-gen/solid-123456-5x5.gen", "/tmp/solid-123456-64x64.gen", "/edith-gen/x.gen", |
| 576 | "/edith-gen/rectangle-zzzzzz-none-0-0-64x64.gen", "/edith-gen/rectangle-ffffff-none-401-0-64x64.gen", "/edith-gen/blob-ffffff-none-1-0-64x64.gen", "/edith-gen/line-none-ffffff-1-0-5x5.gen"] { |
| 577 | assert_eq!(Gen::parse(Path::new(bad)), None, "{bad}"); |
| 578 | } |
| 579 | } |
| 580 | |
| 581 | #[test] |
| 582 | fn a_solid_is_one_colour_and_a_gradient_runs_between_its_two() { |
| 583 | let solid = Gen::new(Kind::Solid { rgb: 0x336699 }, 32, 32).rgb(0); |
| 584 | assert!(solid.chunks_exact(3).all(|p| p == [0x33, 0x66, 0x99])); |
| 585 | let g = Gen::new(Kind::Gradient { a: 0xff0000, b: 0x0000ff, angle: 0 }, 100, 20).rgb(0); |
| 586 | let at = |x: usize| &g[(10 * 100 + x) * 3..][..3]; |
| 587 | assert!(at(0)[0] > 250 && at(0)[2] < 5, "red at the left: {:?}", at(0)); |
| 588 | assert!(at(99)[2] > 250 && at(99)[0] < 5, "blue at the right: {:?}", at(99)); |
| 589 | assert!((i32::from(at(50)[0]) - 128).abs() < 8, "half way in the middle: {:?}", at(50)); |
| 590 | let down = Gen::new(Kind::Gradient { a: 0x000000, b: 0xffffff, angle: 90 }, 20, 100).rgb(0); |
| 591 | assert!(down[..3].iter().all(|v| *v < 6) && down[(99 * 20) * 3] > 250, "top to bottom"); |
| 592 | } |
| 593 | |
| 594 | #[test] |
| 595 | fn bars_are_seven_columns_and_a_countdown_counts_down() { |
| 596 | let b = Gen::new(Kind::Bars, 70, 8).rgb(0); |
| 597 | assert_eq!(&b[..3], [191, 191, 191]); |
| 598 | assert_eq!(&b[(69) * 3..][..3], [0, 0, 191]); |
| 599 | let c = |f| Gen::new(Kind::Countdown { from: 3, milli_fps: 10_000 }, 160, 90).rgb(f); |
| 600 | |
| 601 | assert_ne!(c(0), c(10)); |
| 602 | assert_ne!(c(10), c(20)); |
| 603 | assert_eq!(c(10), c(10)); |
| 604 | assert_ne!(c(0), c(5), "the sweep moves inside a second"); |
| 605 | } |
| 606 | |
| 607 | #[test] |
| 608 | fn shapes_draw_on_a_transparent_canvas() { |
| 609 | let shape = |form, fill, stroke, width, radius| Gen::new(Kind::Shape(Shape { form, fill, stroke, width, radius }), 100, 60); |
| 610 | let at = |a: &[u8], x: usize, y: usize| a[y * 100 + x]; |
| 611 | |
| 612 | let sq = shape(Form::Rectangle, Some(0xff0000), None, 0, 0); |
| 613 | assert!(sq.has_alpha() && sq.alpha().unwrap().iter().all(|a| *a == 255)); |
| 614 | assert!(sq.rgb(0).chunks_exact(3).all(|p| p == [255, 0, 0])); |
| 615 | let round = shape(Form::Rectangle, Some(0xff0000), None, 0, 20).alpha().unwrap(); |
| 616 | assert_eq!(at(&round, 0, 0), 0, "the rounded corner is clear"); |
| 617 | assert_eq!(at(&round, 50, 30), 255); |
| 618 | |
| 619 | let ring = shape(Form::Rectangle, Some(0x0000ff), Some(0x00ff00), 6, 0); |
| 620 | let rgb = ring.rgb(0); |
| 621 | let c = |x: usize, y: usize| &rgb[(y * 100 + x) * 3..][..3]; |
| 622 | assert_eq!(c(50, 2), [0, 255, 0]); |
| 623 | assert_eq!(c(50, 30), [0, 0, 255]); |
| 624 | |
| 625 | let e = shape(Form::Ellipse, Some(0xffffff), None, 0, 0).alpha().unwrap(); |
| 626 | assert_eq!((at(&e, 0, 0), at(&e, 50, 30)), (0, 255)); |
| 627 | let hollow = shape(Form::Ellipse, None, Some(0xffffff), 4, 0).alpha().unwrap(); |
| 628 | assert_eq!((at(&hollow, 50, 30), at(&hollow, 50, 1)), (0, 255)); |
| 629 | |
| 630 | let line = shape(Form::Line, None, Some(0xffffff), 6, 0).alpha().unwrap(); |
| 631 | assert_eq!((at(&line, 50, 30), at(&line, 50, 10), at(&line, 50, 50)), (255, 0, 0)); |
| 632 | let arrow = shape(Form::Arrow, None, Some(0xffffff), 4, 0).alpha().unwrap(); |
| 633 | assert!(at(&arrow, 85, 24) > 200, "the head is wide where the shaft is not"); |
| 634 | assert_eq!(at(&arrow, 30, 24), 0); |
| 635 | |
| 636 | assert!(Gen::new(Kind::Bars, 32, 32).alpha().is_none()); |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn clear_pixels_carry_the_paint_colour_so_scaled_edges_have_no_fringe() { |
| 641 | let g = Gen::new(Kind::Shape(Shape { form: Form::Ellipse, fill: Some(0x336699), stroke: None, width: 0, radius: 0 }), 64, 64); |
| 642 | let (rgb, a) = (g.rgb(0), g.alpha().unwrap()); |
| 643 | assert_eq!(a[0], 0); |
| 644 | assert_eq!(&rgb[..3], [0x33, 0x66, 0x99]); |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | #[cfg(test)] |
| 649 | mod tone_tests { |
| 650 | use super::*; |
| 651 | |
| 652 | fn samples(wav: &[u8]) -> Vec<f64> { |
| 653 | wav[44..].chunks_exact(2).map(|b| f64::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).collect() |
| 654 | } |
| 655 | |
| 656 | |
| 657 | |
| 658 | #[test] |
| 659 | fn the_tone_is_a_sine_at_its_level_and_its_file_is_reused() { |
| 660 | let wav = Tone::DEFAULT.wav(2); |
| 661 | assert_eq!(&wav[0..4], b"RIFF"); |
| 662 | assert_eq!(&wav[8..12], b"WAVE"); |
| 663 | assert_eq!(u32::from_le_bytes([wav[24], wav[25], wav[26], wav[27]]), TONE_RATE); |
| 664 | let s = samples(&wav); |
| 665 | assert_eq!(s.len(), 2 * TONE_RATE as usize); |
| 666 | let db = 20.0 * ((s.iter().map(|v| v * v).sum::<f64>() / s.len() as f64).sqrt()).log10(); |
| 667 | assert!((db + 20.0).abs() < 0.05, "rms {db} dBFS"); |
| 668 | |
| 669 | let crossings = s.windows(2).filter(|w| (w[0] < 0.0) != (w[1] < 0.0)).count(); |
| 670 | assert!((crossings as i64 - 4000).abs() <= 2, "{crossings} crossings"); |
| 671 | |
| 672 | assert_eq!(Tone::new(0, 0), Tone { hz: 20, dbfs: -3 }); |
| 673 | assert_eq!(Tone::new(99_999, -99), Tone { hz: 20_000, dbfs: -60 }); |
| 674 | assert_eq!(Tone::DEFAULT.file_name(10), "tone-1000hz--20dbfs-10s.wav"); |
| 675 | assert_eq!(tone_title(Path::new("/x/tone-1000hz--20dbfs-10s.wav")).as_deref(), Some("Tone 1 kHz \u{b7} \u{2212}20 dB")); |
| 676 | |
| 677 | let dir = crate::scratch::Scratch::dir("tone_file"); |
| 678 | let t = Tone::new(440, -18); |
| 679 | let path = t.write(&dir, 1).expect("writes"); |
| 680 | assert_eq!(std::fs::metadata(&path).unwrap().len(), 44 + 2 * u64::from(TONE_RATE)); |
| 681 | assert_eq!(t.write(&dir, 1).expect("reuses"), path); |
| 682 | } |
| 683 | } |