forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

generate.rs683 lines, 30.3 KiBHistoryRawDownload
1//! Generated clips: pictures made from a few numbers instead of a file -- a solid colour, a
2//! gradient, a countdown, colour bars -- and the adjustment layer, a clip with no picture whose
3//! grade and effects reach everything beneath it.
4//!
5//! A generator is a *source* like any other, so a clip of one is placed, trimmed, graded,
6//! transformed and saved by the machinery every still already goes through. Its "file" is a
7//! pseudo-path that spells the generator out (`/edith-gen/gradient-ff0000-0000ff-45-1920x1080.gen`);
8//! [`is_generated`] recognises it, `is_image` admits it (a generator has a picture, no sound and
9//! no length of its own), and [`crate::decode::Still`] draws it instead of opening a file. Editing
10//! a parameter is a new spelling, so the clip is pointed at the source with the new name.
11//!
12//! The countdown is the one animated kind: its picture depends on the source frame, which
13//! [`Gen::animated`] tells the layered compositor so it asks for each frame afresh.
14
15#![allow(clippy::chunks_exact_to_as_chunks)]
16
17use std::path::{Path, PathBuf};
18
19/// The folder every generator pseudo-path lives in. Never a real directory.
20const DIR: &str = "/edith-gen";
21
22/// The frames-per-second a countdown is spelled with, in millihertz, so the path stays integral.
23const MILLI: f64 = 1000.0;
24
25/// What a generator draws.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Kind {
28 /// One colour, `0xRRGGBB`.
29 Solid { rgb: u32 },
30 /// `a` to `b` along `angle` degrees (0 left to right, 90 top to bottom).
31 Gradient { a: u32, b: u32, angle: u16 },
32 /// Counts down from `from` seconds with a big centred number and a sweep. `milli_fps` is
33 /// the timeline's rate in millihertz, which turns a source frame into a second.
34 Countdown { from: u16, milli_fps: u32 },
35 /// SMPTE-style colour bars.
36 Bars,
37 /// No picture: the clip's grade, effects and transform act on what is composed beneath it.
38 Adjust,
39 /// A drawn shape on a transparent canvas ([`Shape`]).
40 Shape(Shape),
41}
42
43/// What a shape draws.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum Form {
46 /// A box, with `radius` rounding its corners.
47 Rectangle,
48 Ellipse,
49 /// A stroke across the middle of the canvas, left to right, round at both ends.
50 Line,
51 /// A line that ends in a filled head at the right.
52 Arrow,
53}
54
55/// A shape on a transparent canvas: it fills the canvas (the clip's transform sizes and places
56/// it), `fill` inside, `stroke` as a band of `width` pixels along the inside of the edge. A
57/// line and an arrow are all stroke. `None` is no paint, so the canvas shows through.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct Shape {
60 pub form: Form,
61 pub fill: Option<u32>,
62 pub stroke: Option<u32>,
63 /// Stroke width in pixels of the canvas, 0 to 400.
64 pub width: u16,
65 /// Corner radius of a rectangle in pixels of the canvas, 0 to 2000.
66 pub radius: u16,
67}
68
69impl Form {
70 /// The forms a front-end offers, in menu order.
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 /// Whether the form has an inside to fill.
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
101impl Shape {
102 /// The default of a form: a blue fill for the ones that fill, a stroke for the ones that are one.
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 /// The RGBA8 picture, straight alpha, for a `w` x `h` canvas. Transparent pixels carry the
112 /// colour of the nearest paint, so a scaled edge does not pick up a fringe.
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 // The default paint under transparent pixels.
120 let base = stroke.or(fill).unwrap_or([0, 0, 0]);
121 let (cx, cy) = (fw / 2.0, fh / 2.0);
122 // Line and arrow: the stroke is the shape, centred on the middle row, inset from the edges.
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 // Signed distance to the edge: negative inside.
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 // Coverage of the whole shape and of its stroke band.
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
177fn 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/// Distance from `p` to the segment `a`-`b`.
183fn 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/// Signed distance from `p` to the triangle `t` (negative inside).
190fn 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/// A generator and the canvas it is drawn for.
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
200pub struct Gen {
201 pub kind: Kind,
202 pub width: u32,
203 pub height: u32,
204}
205
206/// The kinds a front-end offers by name, in menu order.
207pub const KINDS: [&str; 9] = ["solid", "gradient", "countdown", "bars", "adjust", "rectangle", "ellipse", "line", "arrow"];
208
209impl Kind {
210 /// The word a path, a file and the MCP use.
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 /// The name a person reads on a clip or a library row.
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
235impl 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 /// The default of a kind by name at the canvas `width` x `height` and timeline `fps`.
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 /// Whether the picture depends on the source frame.
254 pub fn animated(&self) -> bool {
255 matches!(self.kind, Kind::Countdown { .. })
256 }
257
258 /// Whether the picture has a transparent background ([`Gen::alpha`]).
259 pub fn has_alpha(&self) -> bool {
260 matches!(self.kind, Kind::Shape(_))
261 }
262
263 /// The scale a new clip of this generator is placed at: a shape lands as a shape on the
264 /// picture, not a full-frame cover.
265 pub fn default_scale(&self) -> Option<f32> {
266 self.has_alpha().then_some(0.4)
267 }
268
269 /// The coverage of each pixel, 0 to 255, for a generator with a transparent background.
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 /// Whether this is the adjustment layer.
276 pub fn is_adjust(&self) -> bool {
277 self.kind == Kind::Adjust
278 }
279
280 /// The pseudo-path that names this generator as a source.
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 /// The generator a pseudo-path spells, `None` for any real path.
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 /// The packed RGB8 picture at source frame `frame`.
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 // The projection of the whole frame on the direction: the corners are t 0 and 1.
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 // 75% white, yellow, cyan, green, magenta, red, blue.
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 /// A film-leader countdown: a dark field, a ring, a lighter sweep that fills the ring once a
391 /// second, and the whole seconds left as a big white numeral in the middle.
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 // Past the end the sweep rests empty rather than looping.
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 // Clockwise from twelve o'clock, 0 to 1.
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 // The numeral goes through the text renderer, on a BGRA copy of the frame.
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
443fn split(rgb: u32) -> [u8; 3] {
444 [(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8]
445}
446
447/// Whether `path` is a generator's pseudo-path rather than a file.
448pub fn is_generated(path: &Path) -> bool {
449 Gen::parse(path).is_some()
450}
451
452/// Whether `path` is the adjustment layer's pseudo-path.
453pub fn is_adjust(path: &Path) -> bool {
454 Gen::parse(path).is_some_and(|g| g.is_adjust())
455}
456
457/// What a source is called where a file name would be shown.
458pub fn title(path: &Path) -> Option<&'static str> {
459 Gen::parse(path).map(|g| g.kind.title())
460}
461
462/// What a tone file is called where a name is shown: "Tone 1 kHz · −20 dB", read back from the
463/// file name `Tone::file_name` made. `None` for any other file.
464pub 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/// A test tone: a sine at `hz` whose RMS level is `dbfs` (broadcast's reading: a sine's RMS is 3 dB
476/// under its peak, so -20 dBFS is a peak of 0.14). It is made once as a mono 16-bit WAV in the
477/// user's data folder and placed like any sound file, so mixing, gain, ducking and export need
478/// nothing new.
479#[derive(Clone, Copy, Debug, PartialEq, Eq)]
480pub struct Tone {
481 /// Hertz, 20 to 20000 and below half the sample rate.
482 pub hz: u32,
483 /// RMS level in whole dB, -60 to -3 (-3 is a peak of full scale).
484 pub dbfs: i32,
485}
486
487/// The sample rate tone files are written at.
488pub const TONE_RATE: u32 = 48_000;
489/// The length a tone is made at when none is asked for, in seconds.
490pub const TONE_SECS: u32 = 10;
491
492impl Tone {
493 /// 1 kHz at -20 dBFS, the reference level.
494 pub const DEFAULT: Tone = Tone { hz: 1000, dbfs: -20 };
495
496 /// The tone as its settings allow: the frequency and level clamped into their ranges.
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 /// The file name the tone of `secs` seconds is kept under.
502 pub fn file_name(&self, secs: u32) -> String {
503 format!("tone-{}hz-{}dbfs-{secs}s.wav", self.hz, self.dbfs)
504 }
505
506 /// The folder tone files of an untitled project are kept in: `$XDG_DATA_HOME/edith/tones`.
507 /// A saved project keeps its tones beside its file instead (the caller chooses).
508 pub fn dir() -> Option<std::path::PathBuf> {
509 Some(Self::dir_in(&crate::templates::data_home()?))
510 }
511
512 /// The tones folder under the data folder `data`.
513 pub fn dir_in(data: &std::path::Path) -> std::path::PathBuf {
514 data.join("edith").join("tones")
515 }
516
517 /// The tone's WAV bytes, `secs` long: 16-bit mono PCM at [`TONE_RATE`].
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()); // PCM
527 out.extend_from_slice(&1u16.to_le_bytes()); // mono
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 /// Writes the tone of `secs` seconds into `dir` (made when missing) and returns its path. A
544 /// file already there is reused, since its name spells out every setting it has.
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)]
557mod 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 // Each second differs (the numeral and the sweep), and a frame repeats exactly.
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 // A filled rectangle covers all of its canvas; with rounded corners the corner is clear.
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 // A stroke runs along the inside of the edge in its own colour; the inside keeps the fill.
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 // An ellipse leaves the corners clear and the centre painted; a stroke-only one is hollow.
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 // A line is a stripe through the middle; an arrow adds a head wider than the stripe.
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 // Every other generator is opaque.
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)]
649mod 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 /// One test for the tone: a 1 kHz sine at -20 dBFS RMS by default, settings clamped, and a
657 /// file written once and reused.
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 // Zero crossings: 1 kHz is 2000 a second.
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}