✨ A burned ASS/SSA track is drawn as libass draws it: styles, PlayRes scaling, outline, shadow, blur, fades, colour/alpha/size/italic overrides, \an and \pos; burn_captions native:false keeps the caption look
Browse files at this commitaf4a6f74f52d24e193193cae44fcff84f07ff5a1Parent: 5d650d95 changed files +1186 -26
- crates/engine/src/assrender.rs +1067 -0
- crates/engine/src/export.rs +86 -20
- crates/engine/src/lib.rs +1 -0
- crates/engine/src/text.rs +22 -3
- crates/mcp/src/tools/export.rs +10 -3
crates/engine/src/assrender.rsadded+1067 -0
| @@ -0,0 +1,1067 @@ | ||
| 1 | +//! Advanced SubStation Alpha drawn as libass draws it: each event in its style's | |
| 2 | +//! face, scaled from `PlayRes` to the frame, with its outline, shadow, blur and | |
| 3 | +//! fade, composed onto the picture. An event's coverage is rasterised once and | |
| 4 | +//! kept while the frame size holds, so a fade is a blend, not a rasterisation. | |
| 5 | + | |
| 6 | +use std::collections::HashMap; | |
| 7 | +use std::path::Path; | |
| 8 | + | |
| 9 | +use ab_glyph::{Font, FontRef, GlyphId, OutlineCurve, point}; | |
| 10 | +use ab_glyph_rasterizer::Rasterizer; | |
| 11 | +use ec_subs::{Segment, SubtitleStyle}; | |
| 12 | + | |
| 13 | +use crate::colorspace::is_sd; | |
| 14 | +use crate::text::{self, mix, yuv}; | |
| 15 | + | |
| 16 | +const ITALIC_SHEAR: f32 = 0.2; | |
| 17 | +const DEFAULT_EVENT_FORMAT: &str = "Layer,Start,End,Style,Name,MarginL,MarginR,MarginV,Effect,Text"; | |
| 18 | + | |
| 19 | +/// One event on screen: its index in the script and its span on the timeline, in microseconds. | |
| 20 | +#[derive(Clone, Copy, Debug)] | |
| 21 | +pub struct Shown { | |
| 22 | + /// The event's index in the script, in file order. | |
| 23 | + pub event: usize, | |
| 24 | + /// When the event starts on the timeline. | |
| 25 | + pub start_us: i64, | |
| 26 | + /// When the event ends on the timeline. | |
| 27 | + pub end_us: i64, | |
| 28 | +} | |
| 29 | + | |
| 30 | +/// An ASS script ready to draw: its PlayRes, styles and events, and the coverage of the events drawn. | |
| 31 | +pub struct Captions { | |
| 32 | + play: (f32, f32), | |
| 33 | + scaled: bool, | |
| 34 | + wrap: u8, | |
| 35 | + styles: Vec<Style>, | |
| 36 | + events: Vec<Event>, | |
| 37 | + cache: HashMap<usize, Drawn>, | |
| 38 | +} | |
| 39 | + | |
| 40 | +impl Captions { | |
| 41 | + /// The script a `.ass` or `.ssa` file holds, or `None` for another file or one that is not a script. | |
| 42 | + pub fn from_file(path: &Path) -> Option<Captions> { | |
| 43 | + let ext = path.extension()?.to_string_lossy().to_ascii_lowercase(); | |
| 44 | + if !matches!(ext.as_str(), "ass" | "ssa") { | |
| 45 | + return None; | |
| 46 | + } | |
| 47 | + Captions::parse(&std::fs::read(path).ok()?) | |
| 48 | + } | |
| 49 | + | |
| 50 | + /// The script in `bytes`, or `None` when it has no events section. | |
| 51 | + pub fn parse(bytes: &[u8]) -> Option<Captions> { | |
| 52 | + let track = ec_ass::parse(bytes).ok()?; | |
| 53 | + let (nums, rows) = scan(&ec_subs::decode(bytes)); | |
| 54 | + let meta = |key: &str| track.metadata.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()); | |
| 55 | + let res = |key: &str, default: f32| { | |
| 56 | + meta(key).and_then(|v| v.parse::<f32>().ok()).filter(|v| *v > 0.0).unwrap_or(default) | |
| 57 | + }; | |
| 58 | + let mut styles: Vec<Style> = track | |
| 59 | + .styles | |
| 60 | + .iter() | |
| 61 | + .map(|s| Style::of(s, nums.get(&s.name).copied())) | |
| 62 | + .collect(); | |
| 63 | + if styles.is_empty() { | |
| 64 | + styles.push(Style::default()); | |
| 65 | + } | |
| 66 | + let events = track | |
| 67 | + .cues | |
| 68 | + .iter() | |
| 69 | + .enumerate() | |
| 70 | + .map(|(i, cue)| { | |
| 71 | + let row = rows.get(i).cloned().unwrap_or_default(); | |
| 72 | + Event { | |
| 73 | + layer: row.layer, | |
| 74 | + style: cue.style_ref.clone(), | |
| 75 | + margins: row.margins, | |
| 76 | + an: row.an, | |
| 77 | + pos: cue.positioning.and_then(|p| p.x.zip(p.y)), | |
| 78 | + segments: cue.segments.clone(), | |
| 79 | + } | |
| 80 | + }) | |
| 81 | + .collect(); | |
| 82 | + Some(Captions { | |
| 83 | + play: (res("play_res_x", 384.0), res("play_res_y", 288.0)), | |
| 84 | + scaled: meta("scaled_border_and_shadow").is_some_and(|v| v.eq_ignore_ascii_case("yes")), | |
| 85 | + wrap: meta("wrap_style").and_then(|v| v.parse().ok()).unwrap_or(0), | |
| 86 | + styles, | |
| 87 | + events, | |
| 88 | + cache: HashMap::new(), | |
| 89 | + }) | |
| 90 | + } | |
| 91 | + | |
| 92 | + /// Draws the events `shown` lists at `t_us` onto a BGRA canvas of `size` pixels. | |
| 93 | + pub fn draw_bgra(&mut self, canvas: &mut [u8], size: (u32, u32), shown: &[Shown], t_us: i64) { | |
| 94 | + let (w, h) = (size.0 as usize, size.1 as usize); | |
| 95 | + if canvas.len() < w * h * 4 { | |
| 96 | + return; | |
| 97 | + } | |
| 98 | + for (event, fade) in self.prepare(size, shown, t_us) { | |
| 99 | + if let Some(d) = self.cache.get(&event) { | |
| 100 | + paint_bgra(d, canvas, (w, h), fade); | |
| 101 | + } | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 105 | + /// Draws the events `shown` lists at `t_us` into I420 planes of `size` pixels. | |
| 106 | + pub fn draw_i420( | |
| 107 | + &mut self, | |
| 108 | + planes: (&mut [u8], &mut [u8], &mut [u8]), | |
| 109 | + size: (u32, u32), | |
| 110 | + full_range: bool, | |
| 111 | + shown: &[Shown], | |
| 112 | + t_us: i64, | |
| 113 | + ) { | |
| 114 | + let (w, h) = (size.0 as usize, size.1 as usize); | |
| 115 | + let cw = w.div_ceil(2); | |
| 116 | + if planes.0.len() < w * h || planes.1.len() < cw * h.div_ceil(2) || planes.2.len() != planes.1.len() { | |
| 117 | + return; | |
| 118 | + } | |
| 119 | + for (event, fade) in self.prepare(size, shown, t_us) { | |
| 120 | + if let Some(d) = self.cache.get(&event) { | |
| 121 | + paint_i420(d, (&mut *planes.0, &mut *planes.1, &mut *planes.2), (w, h), full_range, fade); | |
| 122 | + } | |
| 123 | + } | |
| 124 | + } | |
| 125 | + | |
| 126 | + fn prepare(&mut self, size: (u32, u32), shown: &[Shown], t_us: i64) -> Vec<(usize, u8)> { | |
| 127 | + let mut order: Vec<&Shown> = shown.iter().collect(); | |
| 128 | + order.sort_by_key(|s| (self.events.get(s.event).map_or(0, |e| e.layer), s.event)); | |
| 129 | + self.cache.retain(|k, d| d.size == size && shown.iter().any(|s| s.event == *k)); | |
| 130 | + let mut out = Vec::new(); | |
| 131 | + for s in order { | |
| 132 | + if !self.cache.contains_key(&s.event) { | |
| 133 | + let drawn = self.render(s.event, size).map(|d| (s.event, d)); | |
| 134 | + self.cache.extend(drawn); | |
| 135 | + } | |
| 136 | + if let Some(d) = self.cache.get(&s.event) { | |
| 137 | + out.push((s.event, fade_at(d.fade, t_us - s.start_us, s.end_us - s.start_us))); | |
| 138 | + } | |
| 139 | + } | |
| 140 | + out | |
| 141 | + } | |
| 142 | + | |
| 143 | + fn render(&self, event: usize, (width, height): (u32, u32)) -> Option<Drawn> { | |
| 144 | + let ev = self.events.get(event)?; | |
| 145 | + let style_i = ev | |
| 146 | + .style | |
| 147 | + .as_deref() | |
| 148 | + .and_then(|n| self.styles.iter().position(|s| s.name == n)) | |
| 149 | + .unwrap_or(0); | |
| 150 | + let style = &self.styles[style_i]; | |
| 151 | + let mut walk = Walk { | |
| 152 | + styles: &self.styles, | |
| 153 | + style: style_i, | |
| 154 | + ir: Ir::default(), | |
| 155 | + sticky: Sticky::default(), | |
| 156 | + fade: None, | |
| 157 | + runs: Vec::new(), | |
| 158 | + items: Vec::new(), | |
| 159 | + }; | |
| 160 | + walk.segments(&ev.segments); | |
| 161 | + let faces = walk | |
| 162 | + .runs | |
| 163 | + .iter() | |
| 164 | + .map(|r| Face::of(r.family.as_deref(), r.bold)) | |
| 165 | + .collect::<Option<Vec<Face>>>()?; | |
| 166 | + let style_face = Face::of(style.family.as_deref(), style.bold)?; | |
| 167 | + let (sx, sy) = (width as f32 / self.play.0, height as f32 / self.play.1); | |
| 168 | + let (wf, hf) = (width as f32, height as f32); | |
| 169 | + let margin = |k: usize| (if ev.margins[k] != 0 { ev.margins[k] } else { style.margins[k] }) as f32; | |
| 170 | + let (ml, mr, mv) = (margin(0) * sx, margin(1) * sx, margin(2) * sy); | |
| 171 | + let cells: Vec<Option<Cell>> = walk | |
| 172 | + .items | |
| 173 | + .iter() | |
| 174 | + .map(|item| match *item { | |
| 175 | + Item::Break => None, | |
| 176 | + Item::Char(c, r) => Some(Cell::new(c, r, &walk.runs[r], faces[r], (sx, sy))), | |
| 177 | + }) | |
| 178 | + .collect(); | |
| 179 | + let lines = wrap_lines(cells, (self.wrap != 2).then_some(wf - ml - mr)); | |
| 180 | + let an = ev.an.unwrap_or(style.an); | |
| 181 | + let (col, row) = (usize::from((an - 1) % 3), usize::from((an - 1) / 3)); | |
| 182 | + let lh = style.size * sy; | |
| 183 | + let split = |size: f32, f: &Face| { | |
| 184 | + let h = size * sy; | |
| 185 | + let a = h * f.asc / (f.asc + f.desc).max(1.0); | |
| 186 | + (a, h - a) | |
| 187 | + }; | |
| 188 | + let metrics: Vec<(f32, f32)> = lines | |
| 189 | + .iter() | |
| 190 | + .map(|line| { | |
| 191 | + line.iter() | |
| 192 | + .map(|c| split(walk.runs[c.run].size * walk.runs[c.run].scale_y, &faces[c.run])) | |
| 193 | + .reduce(|p, q| (p.0.max(q.0), p.1.max(q.1))) | |
| 194 | + .unwrap_or_else(|| split(style.size * style.scale_y, &style_face)) | |
| 195 | + }) | |
| 196 | + .collect(); | |
| 197 | + let block: f32 = metrics.iter().map(|(a, d)| a + d).sum(); | |
| 198 | + let anchor_x = match ev.pos { | |
| 199 | + Some((px, _)) => px * sx, | |
| 200 | + None => match col { | |
| 201 | + 0 => ml, | |
| 202 | + 2 => wf - mr, | |
| 203 | + _ => (ml + wf - mr) / 2.0, | |
| 204 | + }, | |
| 205 | + }; | |
| 206 | + let top = match (row, ev.pos.map(|(_, py)| py * sy)) { | |
| 207 | + (0, None) => hf - mv - block, | |
| 208 | + (0, Some(y)) => y - block, | |
| 209 | + (1, None) => (hf - block) / 2.0, | |
| 210 | + (1, Some(y)) => y - block / 2.0, | |
| 211 | + (_, None) => mv, | |
| 212 | + (_, Some(y)) => y, | |
| 213 | + }; | |
| 214 | + let mut placed = Vec::new(); | |
| 215 | + let mut x_range = (f32::INFINITY, f32::NEG_INFINITY); | |
| 216 | + let mut line_top = top; | |
| 217 | + for (line, &(asc, desc)) in lines.iter().zip(&metrics) { | |
| 218 | + let line_w: f32 = line.iter().map(|c| c.adv).sum(); | |
| 219 | + let left = match col { | |
| 220 | + 0 => anchor_x, | |
| 221 | + 1 => anchor_x - line_w / 2.0, | |
| 222 | + _ => anchor_x - line_w, | |
| 223 | + }; | |
| 224 | + x_range = (x_range.0.min(left), x_range.1.max(left + line_w)); | |
| 225 | + let baseline = line_top + asc; | |
| 226 | + line_top += asc + desc; | |
| 227 | + let mut pen = left; | |
| 228 | + for c in line { | |
| 229 | + if c.c != ' ' { | |
| 230 | + placed.push(Placed { | |
| 231 | + run: c.run, | |
| 232 | + font: c.font, | |
| 233 | + id: c.id, | |
| 234 | + x: pen, | |
| 235 | + y: baseline, | |
| 236 | + kx: c.kx, | |
| 237 | + ky: c.ky, | |
| 238 | + shear: c.shear, | |
| 239 | + }); | |
| 240 | + } | |
| 241 | + pen += c.adv; | |
| 242 | + } | |
| 243 | + } | |
| 244 | + if placed.is_empty() { | |
| 245 | + return None; | |
| 246 | + } | |
| 247 | + let (x0, x1) = x_range; | |
| 248 | + let y0 = top; | |
| 249 | + let y1 = top + block; | |
| 250 | + let bsc = if self.scaled { sy } else { 1.0 }; | |
| 251 | + let reach = walk | |
| 252 | + .runs | |
| 253 | + .iter() | |
| 254 | + .map(|r| { | |
| 255 | + let sigma = (r.blur + r.edge_blur) * bsc; | |
| 256 | + r.border.abs() * bsc + r.shadow.abs() * bsc + 3.0 * sigma | |
| 257 | + }) | |
| 258 | + .fold(0.0, f32::max); | |
| 259 | + let pad = (reach + lh * 0.25).ceil() as i32 + 2; | |
| 260 | + let (ox, oy) = (x0.floor() as i32 - pad, y0.floor() as i32 - pad); | |
| 261 | + let mw = (x1.ceil() as i32 + pad - ox).max(1) as usize; | |
| 262 | + let mh = (y1.ceil() as i32 + pad - oy).max(1) as usize; | |
| 263 | + if mw.saturating_mul(mh) > 1 << 26 { | |
| 264 | + return None; | |
| 265 | + } | |
| 266 | + let mut shadows = Vec::new(); | |
| 267 | + let mut outlines = Vec::new(); | |
| 268 | + let mut fills = Vec::new(); | |
| 269 | + for (r, run) in walk.runs.iter().enumerate() { | |
| 270 | + let glyphs: Vec<&Placed> = placed.iter().filter(|p| p.run == r).collect(); | |
| 271 | + if glyphs.is_empty() { | |
| 272 | + continue; | |
| 273 | + } | |
| 274 | + let mut fill = coverage(&glyphs, (mw, mh), (ox as f32, oy as f32)); | |
| 275 | + let border = run.border * bsc; | |
| 276 | + let shadow = (run.shadow * bsc).round() as i32; | |
| 277 | + let sigma = (run.blur + run.edge_blur) * bsc; | |
| 278 | + let mut edge = Vec::new(); | |
| 279 | + if border > 0.0 { | |
| 280 | + edge = dilate(&fill, mw, mh, border); | |
| 281 | + if sigma > 0.0 { | |
| 282 | + edge = gauss(&edge, mw, mh, sigma); | |
| 283 | + } | |
| 284 | + } else if sigma > 0.0 { | |
| 285 | + fill = gauss(&fill, mw, mh, sigma); | |
| 286 | + } | |
| 287 | + if shadow != 0 && run.back[3] > 0 { | |
| 288 | + let base = if border > 0.0 { &edge } else { &fill }; | |
| 289 | + shadows.push(Layer { rgba: run.back, cov: shift(base, mw, mh, shadow, shadow) }); | |
| 290 | + } | |
| 291 | + if border > 0.0 && run.outline[3] > 0 { | |
| 292 | + outlines.push(Layer { rgba: run.outline, cov: edge }); | |
| 293 | + } | |
| 294 | + if run.fill[3] > 0 { | |
| 295 | + fills.push(Layer { rgba: run.fill, cov: fill }); | |
| 296 | + } | |
| 297 | + } | |
| 298 | + Some(Drawn { | |
| 299 | + size: (width, height), | |
| 300 | + x0: ox, | |
| 301 | + y0: oy, | |
| 302 | + w: mw, | |
| 303 | + h: mh, | |
| 304 | + layers: shadows.into_iter().chain(outlines).chain(fills).collect(), | |
| 305 | + fade: walk.fade, | |
| 306 | + }) | |
| 307 | + } | |
| 308 | +} | |
| 309 | + | |
| 310 | +#[derive(Clone, Debug)] | |
| 311 | +struct Drawn { | |
| 312 | + size: (u32, u32), | |
| 313 | + x0: i32, | |
| 314 | + y0: i32, | |
| 315 | + w: usize, | |
| 316 | + h: usize, | |
| 317 | + layers: Vec<Layer>, | |
| 318 | + fade: Option<(i64, i64)>, | |
| 319 | +} | |
| 320 | + | |
| 321 | +#[derive(Clone, Debug)] | |
| 322 | +struct Layer { | |
| 323 | + rgba: [u8; 4], | |
| 324 | + cov: Vec<u8>, | |
| 325 | +} | |
| 326 | + | |
| 327 | +#[derive(Clone, Debug)] | |
| 328 | +struct Event { | |
| 329 | + layer: i32, | |
| 330 | + style: Option<String>, | |
| 331 | + margins: [i32; 3], | |
| 332 | + an: Option<u8>, | |
| 333 | + pos: Option<(f32, f32)>, | |
| 334 | + segments: Vec<Segment>, | |
| 335 | +} | |
| 336 | + | |
| 337 | +#[derive(Clone, Debug)] | |
| 338 | +struct Style { | |
| 339 | + name: String, | |
| 340 | + family: Option<String>, | |
| 341 | + size: f32, | |
| 342 | + primary: [u8; 4], | |
| 343 | + outline: [u8; 4], | |
| 344 | + back: [u8; 4], | |
| 345 | + bold: bool, | |
| 346 | + italic: bool, | |
| 347 | + scale_x: f32, | |
| 348 | + scale_y: f32, | |
| 349 | + spacing: f32, | |
| 350 | + border: f32, | |
| 351 | + shadow: f32, | |
| 352 | + an: u8, | |
| 353 | + margins: [i32; 3], | |
| 354 | +} | |
| 355 | + | |
| 356 | +impl Default for Style { | |
| 357 | + fn default() -> Self { | |
| 358 | + Style { | |
| 359 | + name: String::new(), | |
| 360 | + family: None, | |
| 361 | + size: 20.0, | |
| 362 | + primary: [255; 4], | |
| 363 | + outline: [0, 0, 0, 255], | |
| 364 | + back: [0, 0, 0, 128], | |
| 365 | + bold: false, | |
| 366 | + italic: false, | |
| 367 | + scale_x: 1.0, | |
| 368 | + scale_y: 1.0, | |
| 369 | + spacing: 0.0, | |
| 370 | + border: 2.0, | |
| 371 | + shadow: 2.0, | |
| 372 | + an: 2, | |
| 373 | + margins: [10; 3], | |
| 374 | + } | |
| 375 | + } | |
| 376 | +} | |
| 377 | + | |
| 378 | +impl Style { | |
| 379 | + fn of(s: &SubtitleStyle, n: Option<Nums>) -> Style { | |
| 380 | + let n = n.unwrap_or_default(); | |
| 381 | + let rgba = |c: Option<(u8, u8, u8, u8)>, default: [u8; 4]| c.map_or(default, |(r, g, b, a)| [r, g, b, a]); | |
| 382 | + let d = Style::default(); | |
| 383 | + Style { | |
| 384 | + name: s.name.clone(), | |
| 385 | + family: s.font_family.clone(), | |
| 386 | + size: s.font_size.unwrap_or(d.size), | |
| 387 | + primary: rgba(s.primary_color, d.primary), | |
| 388 | + outline: rgba(s.outline_color, d.outline), | |
| 389 | + back: rgba(s.back_color, d.back), | |
| 390 | + bold: s.bold, | |
| 391 | + italic: s.italic, | |
| 392 | + scale_x: n.scale_x, | |
| 393 | + scale_y: n.scale_y, | |
| 394 | + spacing: n.spacing, | |
| 395 | + border: s.outline.unwrap_or(0.0), | |
| 396 | + shadow: s.shadow.unwrap_or(0.0), | |
| 397 | + an: n.an, | |
| 398 | + margins: [s.margin_l.unwrap_or(0), s.margin_r.unwrap_or(0), s.margin_v.unwrap_or(0)], | |
| 399 | + } | |
| 400 | + } | |
| 401 | +} | |
| 402 | + | |
| 403 | +#[derive(Clone, Copy)] | |
| 404 | +struct Nums { | |
| 405 | + scale_x: f32, | |
| 406 | + scale_y: f32, | |
| 407 | + spacing: f32, | |
| 408 | + an: u8, | |
| 409 | +} | |
| 410 | + | |
| 411 | +impl Default for Nums { | |
| 412 | + fn default() -> Self { | |
| 413 | + Nums { scale_x: 1.0, scale_y: 1.0, spacing: 0.0, an: 2 } | |
| 414 | + } | |
| 415 | +} | |
| 416 | + | |
| 417 | +#[derive(Clone, Default)] | |
| 418 | +struct Row { | |
| 419 | + layer: i32, | |
| 420 | + margins: [i32; 3], | |
| 421 | + an: Option<u8>, | |
| 422 | +} | |
| 423 | + | |
| 424 | +fn scan(text: &str) -> (HashMap<String, Nums>, Vec<Row>) { | |
| 425 | + let mut nums = HashMap::new(); | |
| 426 | + let mut rows = Vec::new(); | |
| 427 | + let mut section = String::new(); | |
| 428 | + let mut style_format: Vec<String> = Vec::new(); | |
| 429 | + let mut event_format: Vec<String> = Vec::new(); | |
| 430 | + for line in text.lines() { | |
| 431 | + let t = line.trim(); | |
| 432 | + if let Some(name) = t.strip_prefix('[').and_then(|s| s.strip_suffix(']')) { | |
| 433 | + section = name.trim().to_ascii_lowercase(); | |
| 434 | + continue; | |
| 435 | + } | |
| 436 | + let Some((key, value)) = t.split_once(':') else { | |
| 437 | + continue; | |
| 438 | + }; | |
| 439 | + let (key, value) = (key.trim(), value.trim()); | |
| 440 | + let styles = section.ends_with("styles"); | |
| 441 | + if styles && key == "Format" { | |
| 442 | + style_format = fields(value); | |
| 443 | + } else if styles && key == "Style" { | |
| 444 | + let values: Vec<&str> = value.split(',').collect(); | |
| 445 | + if let Some(name) = column(&style_format, &values, "Name") { | |
| 446 | + nums.insert(name.to_owned(), Nums::of(&style_format, &values, section == "v4 styles")); | |
| 447 | + } | |
| 448 | + } else if section == "events" && key == "Format" { | |
| 449 | + event_format = fields(value); | |
| 450 | + } else if section == "events" && key == "Dialogue" { | |
| 451 | + rows.extend(dialogue_row(&event_format, value)); | |
| 452 | + } | |
| 453 | + } | |
| 454 | + (nums, rows) | |
| 455 | +} | |
| 456 | + | |
| 457 | +fn fields(value: &str) -> Vec<String> { | |
| 458 | + value.split(',').map(|f| f.trim().to_owned()).collect() | |
| 459 | +} | |
| 460 | + | |
| 461 | +fn column<'a>(format: &[String], values: &[&'a str], name: &str) -> Option<&'a str> { | |
| 462 | + let at = format.iter().position(|f| f.eq_ignore_ascii_case(name))?; | |
| 463 | + values.get(at).copied().map(str::trim) | |
| 464 | +} | |
| 465 | + | |
| 466 | +impl Nums { | |
| 467 | + fn of(format: &[String], values: &[&str], v4: bool) -> Nums { | |
| 468 | + let num = |key: &str| column(format, values, key).and_then(|v| v.parse::<f32>().ok()); | |
| 469 | + let code = column(format, values, "Alignment").and_then(|v| v.parse::<i32>().ok()).unwrap_or(2); | |
| 470 | + let an = if v4 { | |
| 471 | + ssa_numpad(code) | |
| 472 | + } else if (1..=9).contains(&code) { | |
| 473 | + code as u8 | |
| 474 | + } else { | |
| 475 | + 2 | |
| 476 | + }; | |
| 477 | + Nums { | |
| 478 | + scale_x: num("ScaleX").unwrap_or(100.0) / 100.0, | |
| 479 | + scale_y: num("ScaleY").unwrap_or(100.0) / 100.0, | |
| 480 | + spacing: num("Spacing").unwrap_or(0.0), | |
| 481 | + an, | |
| 482 | + } | |
| 483 | + } | |
| 484 | +} | |
| 485 | + | |
| 486 | +fn ssa_numpad(code: i32) -> u8 { | |
| 487 | + let col = match code & 3 { | |
| 488 | + 1 => 0, | |
| 489 | + 3 => 2, | |
| 490 | + _ => 1, | |
| 491 | + }; | |
| 492 | + let row = if code & 4 != 0 { | |
| 493 | + 2 | |
| 494 | + } else if code & 8 != 0 { | |
| 495 | + 1 | |
| 496 | + } else { | |
| 497 | + 0 | |
| 498 | + }; | |
| 499 | + (row * 3 + col + 1) as u8 | |
| 500 | +} | |
| 501 | + | |
| 502 | +fn dialogue_row(format: &[String], value: &str) -> Option<Row> { | |
| 503 | + let format = if format.is_empty() { fields(DEFAULT_EVENT_FORMAT) } else { format.to_vec() }; | |
| 504 | + let values: Vec<&str> = value.splitn(format.len(), ',').collect(); | |
| 505 | + column(&format, &values, "Start").and_then(ec_subs::parse_clock)?; | |
| 506 | + column(&format, &values, "End").and_then(ec_subs::parse_clock)?; | |
| 507 | + let int = |key: &str| column(&format, &values, key).and_then(|v| v.parse::<i32>().ok()).unwrap_or(0); | |
| 508 | + Some(Row { | |
| 509 | + layer: int("Layer"), | |
| 510 | + margins: [int("MarginL"), int("MarginR"), int("MarginV")], | |
| 511 | + an: column(&format, &values, "Text").and_then(an_tag), | |
| 512 | + }) | |
| 513 | +} | |
| 514 | + | |
| 515 | +fn an_tag(text: &str) -> Option<u8> { | |
| 516 | + let at = text.find("\\an")?; | |
| 517 | + text[at + 3..] | |
| 518 | + .chars() | |
| 519 | + .next()? | |
| 520 | + .to_digit(10) | |
| 521 | + .filter(|d| (1..=9).contains(d)) | |
| 522 | + .map(|d| d as u8) | |
| 523 | +} | |
| 524 | + | |
| 525 | +fn hex(arg: &str) -> Option<u32> { | |
| 526 | + let digits = arg.trim().trim_matches('&').trim_start_matches(['H', 'h']); | |
| 527 | + u32::from_str_radix(digits, 16).ok() | |
| 528 | +} | |
| 529 | + | |
| 530 | +fn colour(arg: &str) -> Option<[u8; 4]> { | |
| 531 | + let v = hex(arg)?; | |
| 532 | + Some([(v & 0xFF) as u8, ((v >> 8) & 0xFF) as u8, ((v >> 16) & 0xFF) as u8, 255 - ((v >> 24) & 0xFF) as u8]) | |
| 533 | +} | |
| 534 | + | |
| 535 | +fn alpha(arg: &str) -> Option<u8> { | |
| 536 | + hex(arg).map(|v| 255 - (v & 0xFF) as u8) | |
| 537 | +} | |
| 538 | + | |
| 539 | +#[derive(Clone, Default)] | |
| 540 | +struct Ir { | |
| 541 | + bold: bool, | |
| 542 | + italic: bool, | |
| 543 | + colour: Option<[u8; 3]>, | |
| 544 | + family: Option<String>, | |
| 545 | + size: Option<f32>, | |
| 546 | +} | |
| 547 | + | |
| 548 | +#[derive(Clone, Default)] | |
| 549 | +struct Sticky { | |
| 550 | + fill_a: Option<u8>, | |
| 551 | + outline_a: Option<u8>, | |
| 552 | + back_a: Option<u8>, | |
| 553 | + outline: Option<[u8; 3]>, | |
| 554 | + back: Option<[u8; 3]>, | |
| 555 | + border: Option<f32>, | |
| 556 | + shadow: Option<f32>, | |
| 557 | + blur: Option<f32>, | |
| 558 | + edge_blur: Option<u32>, | |
| 559 | +} | |
| 560 | + | |
| 561 | +#[derive(Clone)] | |
| 562 | +struct Run { | |
| 563 | + family: Option<String>, | |
| 564 | + size: f32, | |
| 565 | + bold: bool, | |
| 566 | + italic: bool, | |
| 567 | + fill: [u8; 4], | |
| 568 | + outline: [u8; 4], | |
| 569 | + back: [u8; 4], | |
| 570 | + border: f32, | |
| 571 | + shadow: f32, | |
| 572 | + blur: f32, | |
| 573 | + edge_blur: f32, | |
| 574 | + scale_x: f32, | |
| 575 | + scale_y: f32, | |
| 576 | + spacing: f32, | |
| 577 | +} | |
| 578 | + | |
| 579 | +enum Item { | |
| 580 | + Char(char, usize), | |
| 581 | + Break, | |
| 582 | +} | |
| 583 | + | |
| 584 | +struct Walk<'a> { | |
| 585 | + styles: &'a [Style], | |
| 586 | + style: usize, | |
| 587 | + ir: Ir, | |
| 588 | + sticky: Sticky, | |
| 589 | + fade: Option<(i64, i64)>, | |
| 590 | + runs: Vec<Run>, | |
| 591 | + items: Vec<Item>, | |
| 592 | +} | |
| 593 | + | |
| 594 | +impl Walk<'_> { | |
| 595 | + fn segments(&mut self, segments: &[Segment]) { | |
| 596 | + for segment in segments { | |
| 597 | + self.segment(segment); | |
| 598 | + } | |
| 599 | + } | |
| 600 | + | |
| 601 | + fn segment(&mut self, segment: &Segment) { | |
| 602 | + match segment { | |
| 603 | + Segment::Text(text) => { | |
| 604 | + let run = self.run(); | |
| 605 | + self.items.extend(text.chars().map(|c| Item::Char(c, run))); | |
| 606 | + } | |
| 607 | + Segment::LineBreak => self.items.push(Item::Break), | |
| 608 | + Segment::Bold(children) => self.nested(children, |ir| ir.bold = true), | |
| 609 | + Segment::Italic(children) => self.nested(children, |ir| ir.italic = true), | |
| 610 | + Segment::Underline(children) | Segment::Strike(children) => self.segments(children), | |
| 611 | + Segment::Voice { children, .. } | Segment::Class { children, .. } => self.segments(children), | |
| 612 | + Segment::Karaoke { children, .. } => self.segments(children), | |
| 613 | + Segment::Color { rgb, children } => { | |
| 614 | + let rgb = *rgb; | |
| 615 | + self.nested(children, move |ir| ir.colour = Some([rgb.0, rgb.1, rgb.2])); | |
| 616 | + } | |
| 617 | + Segment::Font { family, size, children } => { | |
| 618 | + let (family, size) = (family.clone(), *size); | |
| 619 | + self.nested(children, move |ir| { | |
| 620 | + if family.is_some() { | |
| 621 | + ir.family = family; | |
| 622 | + } | |
| 623 | + if size.is_some() { | |
| 624 | + ir.size = size; | |
| 625 | + } | |
| 626 | + }); | |
| 627 | + } | |
| 628 | + Segment::Raw(text) => { | |
| 629 | + if let Some(block) = text.strip_prefix('{') { | |
| 630 | + self.block(block.trim_end_matches('}')); | |
| 631 | + } | |
| 632 | + } | |
| 633 | + Segment::Timestamp { .. } => {} | |
| 634 | + } | |
| 635 | + } | |
| 636 | + | |
| 637 | + fn nested(&mut self, children: &[Segment], set: impl FnOnce(&mut Ir)) { | |
| 638 | + let saved = self.ir.clone(); | |
| 639 | + set(&mut self.ir); | |
| 640 | + self.segments(children); | |
| 641 | + self.ir = saved; | |
| 642 | + } | |
| 643 | + | |
| 644 | + fn block(&mut self, body: &str) { | |
| 645 | + for tag in body.split('\\').map(str::trim).filter(|t| !t.is_empty()) { | |
| 646 | + self.tag(tag); | |
| 647 | + } | |
| 648 | + } | |
| 649 | + | |
| 650 | + fn tag(&mut self, tag: &str) { | |
| 651 | + if let Some(name) = tag.strip_prefix('r') { | |
| 652 | + self.style = self | |
| 653 | + .styles | |
| 654 | + .iter() | |
| 655 | + .position(|s| s.name == name.trim()) | |
| 656 | + .unwrap_or(self.style); | |
| 657 | + self.ir = Ir::default(); | |
| 658 | + self.sticky = Sticky::default(); | |
| 659 | + return; | |
| 660 | + } | |
| 661 | + let k = &mut self.sticky; | |
| 662 | + if let Some(arg) = tag.strip_prefix("alpha") { | |
| 663 | + if let Some(a) = alpha(arg) { | |
| 664 | + k.fill_a = Some(a); | |
| 665 | + k.outline_a = Some(a); | |
| 666 | + k.back_a = Some(a); | |
| 667 | + } | |
| 668 | + } else if let Some(arg) = tag.strip_prefix("1a") { | |
| 669 | + k.fill_a = alpha(arg).or(k.fill_a); | |
| 670 | + } else if let Some(arg) = tag.strip_prefix("3a") { | |
| 671 | + k.outline_a = alpha(arg).or(k.outline_a); | |
| 672 | + } else if let Some(arg) = tag.strip_prefix("4a") { | |
| 673 | + k.back_a = alpha(arg).or(k.back_a); | |
| 674 | + } else if let Some(arg) = tag.strip_prefix("3c") { | |
| 675 | + k.outline = colour(arg).map(|c| [c[0], c[1], c[2]]).or(k.outline); | |
| 676 | + } else if let Some(arg) = tag.strip_prefix("4c") { | |
| 677 | + k.back = colour(arg).map(|c| [c[0], c[1], c[2]]).or(k.back); | |
| 678 | + } else if let Some(arg) = tag.strip_prefix("bord") { | |
| 679 | + k.border = arg.trim().parse().ok().or(k.border); | |
| 680 | + } else if let Some(arg) = tag.strip_prefix("shad") { | |
| 681 | + k.shadow = arg.trim().parse().ok().or(k.shadow); | |
| 682 | + } else if let Some(arg) = tag.strip_prefix("blur") { | |
| 683 | + k.blur = arg.trim().parse().ok().or(k.blur); | |
| 684 | + } else if let Some(arg) = tag.strip_prefix("be") { | |
| 685 | + k.edge_blur = arg.trim().parse().ok().or(k.edge_blur); | |
| 686 | + } else if let Some(arg) = tag.strip_prefix("fad") { | |
| 687 | + let times: Vec<i64> = arg | |
| 688 | + .trim_matches(['(', ')']) | |
| 689 | + .split(',') | |
| 690 | + .filter_map(|n| n.trim().parse().ok()) | |
| 691 | + .collect(); | |
| 692 | + if let [fin, fout] = times[..] { | |
| 693 | + self.fade = Some((fin, fout)); | |
| 694 | + } | |
| 695 | + } | |
| 696 | + } | |
| 697 | + | |
| 698 | + fn run(&mut self) -> usize { | |
| 699 | + let s = &self.styles[self.style]; | |
| 700 | + let (ir, k) = (&self.ir, &self.sticky); | |
| 701 | + let rgb = |c: Option<[u8; 3]>, base: [u8; 4]| c.unwrap_or([base[0], base[1], base[2]]); | |
| 702 | + let run = Run { | |
| 703 | + family: ir.family.clone().or_else(|| s.family.clone()), | |
| 704 | + size: ir.size.unwrap_or(s.size), | |
| 705 | + bold: ir.bold || s.bold, | |
| 706 | + italic: ir.italic || s.italic, | |
| 707 | + fill: with_alpha(rgb(ir.colour, s.primary), k.fill_a.unwrap_or(s.primary[3])), | |
| 708 | + outline: with_alpha(rgb(k.outline, s.outline), k.outline_a.unwrap_or(s.outline[3])), | |
| 709 | + back: with_alpha(rgb(k.back, s.back), k.back_a.unwrap_or(s.back[3])), | |
| 710 | + border: k.border.unwrap_or(s.border), | |
| 711 | + shadow: k.shadow.unwrap_or(s.shadow), | |
| 712 | + blur: k.blur.unwrap_or(0.0), | |
| 713 | + edge_blur: k.edge_blur.unwrap_or(0) as f32, | |
| 714 | + scale_x: s.scale_x, | |
| 715 | + scale_y: s.scale_y, | |
| 716 | + spacing: s.spacing, | |
| 717 | + }; | |
| 718 | + self.runs.push(run); | |
| 719 | + self.runs.len() - 1 | |
| 720 | + } | |
| 721 | +} | |
| 722 | + | |
| 723 | +fn with_alpha(rgb: [u8; 3], a: u8) -> [u8; 4] { | |
| 724 | + [rgb[0], rgb[1], rgb[2], a] | |
| 725 | +} | |
| 726 | + | |
| 727 | +#[derive(Clone, Copy)] | |
| 728 | +struct Face { | |
| 729 | + font: &'static FontRef<'static>, | |
| 730 | + asc: f32, | |
| 731 | + desc: f32, | |
| 732 | +} | |
| 733 | + | |
| 734 | +impl Face { | |
| 735 | + fn of(name: Option<&str>, bold: bool) -> Option<Face> { | |
| 736 | + let family = name.and_then(text::family_face).or_else(|| text::bundled_family(bold))?; | |
| 737 | + let (font, data, index) = family.parts(); | |
| 738 | + let (asc, desc) = vertical(data, index); | |
| 739 | + Some(Face { font, asc, desc }) | |
| 740 | + } | |
| 741 | +} | |
| 742 | + | |
| 743 | +fn vertical(data: &[u8], index: u32) -> (f32, f32) { | |
| 744 | + let Ok(face) = ttf_parser::Face::parse(data, index) else { | |
| 745 | + return (0.8, 0.2); | |
| 746 | + }; | |
| 747 | + if let Some(os2) = face.tables().os2.as_ref() { | |
| 748 | + let (asc, desc) = (f32::from(os2.windows_ascender()), -f32::from(os2.windows_descender())); | |
| 749 | + if asc + desc > 0.0 { | |
| 750 | + return (asc, desc); | |
| 751 | + } | |
| 752 | + } | |
| 753 | + (f32::from(face.ascender()), -f32::from(face.descender())) | |
| 754 | +} | |
| 755 | + | |
| 756 | +fn glyph(font: &'static FontRef<'static>, c: char) -> (&'static FontRef<'static>, GlyphId) { | |
| 757 | + let id = font.glyph_id(c); | |
| 758 | + if id.0 != 0 { | |
| 759 | + return (font, id); | |
| 760 | + } | |
| 761 | + let fallback = text::bundled_family(false).map_or(font, |f| f.parts().0); | |
| 762 | + (fallback, fallback.glyph_id(c)) | |
| 763 | +} | |
| 764 | + | |
| 765 | +struct Cell { | |
| 766 | + c: char, | |
| 767 | + run: usize, | |
| 768 | + font: &'static FontRef<'static>, | |
| 769 | + id: GlyphId, | |
| 770 | + adv: f32, | |
| 771 | + kx: f32, | |
| 772 | + ky: f32, | |
| 773 | + shear: f32, | |
| 774 | +} | |
| 775 | + | |
| 776 | +impl Cell { | |
| 777 | + fn new(c: char, run: usize, r: &Run, face: Face, (sx, sy): (f32, f32)) -> Cell { | |
| 778 | + let (font, id) = glyph(face.font, c); | |
| 779 | + let scale = r.size / (face.asc + face.desc).max(1.0); | |
| 780 | + let kx = sx * r.scale_x * scale; | |
| 781 | + let ky = sy * r.scale_y * scale; | |
| 782 | + Cell { | |
| 783 | + c, | |
| 784 | + run, | |
| 785 | + font, | |
| 786 | + id, | |
| 787 | + adv: font.h_advance_unscaled(id) * kx + r.spacing * sx, | |
| 788 | + kx, | |
| 789 | + ky, | |
| 790 | + shear: if r.italic { ITALIC_SHEAR } else { 0.0 }, | |
| 791 | + } | |
| 792 | + } | |
| 793 | +} | |
| 794 | + | |
| 795 | +struct Placed { | |
| 796 | + run: usize, | |
| 797 | + font: &'static FontRef<'static>, | |
| 798 | + id: GlyphId, | |
| 799 | + x: f32, | |
| 800 | + y: f32, | |
| 801 | + kx: f32, | |
| 802 | + ky: f32, | |
| 803 | + shear: f32, | |
| 804 | +} | |
| 805 | + | |
| 806 | +fn wrap_lines(cells: Vec<Option<Cell>>, max: Option<f32>) -> Vec<Vec<Cell>> { | |
| 807 | + let mut lines = Lines { max, done: Vec::new(), line: Vec::new(), width: 0.0 }; | |
| 808 | + let mut word = Vec::new(); | |
| 809 | + for cell in cells { | |
| 810 | + match cell { | |
| 811 | + None => { | |
| 812 | + lines.word(&mut word); | |
| 813 | + lines.end(); | |
| 814 | + } | |
| 815 | + Some(c) if c.c == ' ' => { | |
| 816 | + lines.word(&mut word); | |
| 817 | + lines.width += c.adv; | |
| 818 | + lines.line.push(c); | |
| 819 | + } | |
| 820 | + Some(c) => word.push(c), | |
| 821 | + } | |
| 822 | + } | |
| 823 | + lines.word(&mut word); | |
| 824 | + lines.end(); | |
| 825 | + lines.done | |
| 826 | +} | |
| 827 | + | |
| 828 | +struct Lines { | |
| 829 | + max: Option<f32>, | |
| 830 | + done: Vec<Vec<Cell>>, | |
| 831 | + line: Vec<Cell>, | |
| 832 | + width: f32, | |
| 833 | +} | |
| 834 | + | |
| 835 | +impl Lines { | |
| 836 | + fn word(&mut self, word: &mut Vec<Cell>) { | |
| 837 | + if word.is_empty() { | |
| 838 | + return; | |
| 839 | + } | |
| 840 | + let w: f32 = word.iter().map(|c| c.adv).sum(); | |
| 841 | + if self.max.is_some_and(|m| self.width + w > m) && self.line.iter().any(|c| c.c != ' ') { | |
| 842 | + self.end(); | |
| 843 | + } | |
| 844 | + self.width += w; | |
| 845 | + self.line.append(word); | |
| 846 | + } | |
| 847 | + | |
| 848 | + fn end(&mut self) { | |
| 849 | + while let Some(c) = self.line.last().filter(|c| c.c == ' ') { | |
| 850 | + self.width -= c.adv; | |
| 851 | + self.line.pop(); | |
| 852 | + } | |
| 853 | + self.done.push(std::mem::take(&mut self.line)); | |
| 854 | + self.width = 0.0; | |
| 855 | + } | |
| 856 | +} | |
| 857 | + | |
| 858 | +fn draw_glyph(ras: &mut Rasterizer, p: &Placed, (ox, oy): (f32, f32)) { | |
| 859 | + let Some(outline) = p.font.outline(p.id) else { | |
| 860 | + return; | |
| 861 | + }; | |
| 862 | + let map = |q: ab_glyph::Point| point(p.x - ox + p.kx * (q.x + p.shear * q.y), p.y - oy - p.ky * q.y); | |
| 863 | + for curve in outline.curves { | |
| 864 | + match curve { | |
| 865 | + OutlineCurve::Line(a, b) => ras.draw_line(map(a), map(b)), | |
| 866 | + OutlineCurve::Quad(a, b, c) => ras.draw_quad(map(a), map(b), map(c)), | |
| 867 | + OutlineCurve::Cubic(a, b, c, d) => ras.draw_cubic(map(a), map(b), map(c), map(d)), | |
| 868 | + } | |
| 869 | + } | |
| 870 | +} | |
| 871 | + | |
| 872 | +fn coverage(glyphs: &[&Placed], (w, h): (usize, usize), origin: (f32, f32)) -> Vec<u8> { | |
| 873 | + let mut ras = Rasterizer::new(w, h); | |
| 874 | + for p in glyphs { | |
| 875 | + draw_glyph(&mut ras, p, origin); | |
| 876 | + } | |
| 877 | + let mut out = vec![0u8; w * h]; | |
| 878 | + ras.for_each_pixel_2d(|x, y, c| { | |
| 879 | + out[y as usize * w + x as usize] = (c.clamp(0.0, 1.0) * 255.0).round() as u8; | |
| 880 | + }); | |
| 881 | + out | |
| 882 | +} | |
| 883 | + | |
| 884 | +fn dilate(src: &[u8], w: usize, h: usize, r: f32) -> Vec<u8> { | |
| 885 | + let n = r.ceil() as i32; | |
| 886 | + let mut taps = Vec::new(); | |
| 887 | + for dy in -n..=n { | |
| 888 | + for dx in -n..=n { | |
| 889 | + let d = ((dx * dx + dy * dy) as f32).sqrt(); | |
| 890 | + let weight = (r + 0.5 - d).clamp(0.0, 1.0); | |
| 891 | + if weight > 0.0 { | |
| 892 | + taps.push((dx, dy, weight)); | |
| 893 | + } | |
| 894 | + } | |
| 895 | + } | |
| 896 | + let mut out = vec![0u8; w * h]; | |
| 897 | + for y in 0..h { | |
| 898 | + for x in 0..w { | |
| 899 | + let mut best = 0f32; | |
| 900 | + for &(dx, dy, weight) in &taps { | |
| 901 | + let (sx, sy) = (x as i32 + dx, y as i32 + dy); | |
| 902 | + if sx < 0 || sy < 0 || sx >= w as i32 || sy >= h as i32 { | |
| 903 | + continue; | |
| 904 | + } | |
| 905 | + best = best.max(f32::from(src[sy as usize * w + sx as usize]) * weight); | |
| 906 | + } | |
| 907 | + out[y * w + x] = best.round() as u8; | |
| 908 | + } | |
| 909 | + } | |
| 910 | + out | |
| 911 | +} | |
| 912 | + | |
| 913 | +fn gauss(src: &[u8], w: usize, h: usize, sigma: f32) -> Vec<u8> { | |
| 914 | + let n = (3.0 * sigma).ceil() as isize; | |
| 915 | + let k: Vec<f32> = (-n..=n) | |
| 916 | + .map(|i| (-((i * i) as f32) / (2.0 * sigma * sigma)).exp()) | |
| 917 | + .collect(); | |
| 918 | + let total: f32 = k.iter().sum(); | |
| 919 | + let mut tmp = vec![0f32; w * h]; | |
| 920 | + for y in 0..h { | |
| 921 | + for x in 0..w { | |
| 922 | + let mut acc = 0f32; | |
| 923 | + for (j, kv) in k.iter().enumerate() { | |
| 924 | + let sx = x as isize + j as isize - n; | |
| 925 | + if (0..w as isize).contains(&sx) { | |
| 926 | + acc += kv * f32::from(src[y * w + sx as usize]); | |
| 927 | + } | |
| 928 | + } | |
| 929 | + tmp[y * w + x] = acc / total; | |
| 930 | + } | |
| 931 | + } | |
| 932 | + let mut out = vec![0u8; w * h]; | |
| 933 | + for y in 0..h { | |
| 934 | + for x in 0..w { | |
| 935 | + let mut acc = 0f32; | |
| 936 | + for (j, kv) in k.iter().enumerate() { | |
| 937 | + let sy = y as isize + j as isize - n; | |
| 938 | + if (0..h as isize).contains(&sy) { | |
| 939 | + acc += kv * tmp[sy as usize * w + x]; | |
| 940 | + } | |
| 941 | + } | |
| 942 | + out[y * w + x] = (acc / total).round().clamp(0.0, 255.0) as u8; | |
| 943 | + } | |
| 944 | + } | |
| 945 | + out | |
| 946 | +} | |
| 947 | + | |
| 948 | +fn shift(src: &[u8], w: usize, h: usize, dx: i32, dy: i32) -> Vec<u8> { | |
| 949 | + let mut out = vec![0u8; w * h]; | |
| 950 | + for y in 0..h { | |
| 951 | + let sy = y as i32 - dy; | |
| 952 | + if sy < 0 || sy >= h as i32 { | |
| 953 | + continue; | |
| 954 | + } | |
| 955 | + for x in 0..w { | |
| 956 | + let sx = x as i32 - dx; | |
| 957 | + if sx >= 0 && sx < w as i32 { | |
| 958 | + out[y * w + x] = src[sy as usize * w + sx as usize]; | |
| 959 | + } | |
| 960 | + } | |
| 961 | + } | |
| 962 | + out | |
| 963 | +} | |
| 964 | + | |
| 965 | +fn fade_at(fade: Option<(i64, i64)>, t: i64, dur: i64) -> u8 { | |
| 966 | + let Some((fin, fout)) = fade.map(|(i, o)| (i * 1000, o * 1000)) else { | |
| 967 | + return 255; | |
| 968 | + }; | |
| 969 | + let mut k = 1.0f32; | |
| 970 | + if fin > 0 && t < fin { | |
| 971 | + k = k.min(t as f32 / fin as f32); | |
| 972 | + } | |
| 973 | + if fout > 0 && dur - t < fout { | |
| 974 | + k = k.min((dur - t) as f32 / fout as f32); | |
| 975 | + } | |
| 976 | + (k.clamp(0.0, 1.0) * 255.0).round() as u8 | |
| 977 | +} | |
| 978 | + | |
| 979 | +fn mul(a: u8, b: u8) -> u8 { | |
| 980 | + ((u16::from(a) * u16::from(b) + 127) / 255) as u8 | |
| 981 | +} | |
| 982 | + | |
| 983 | +fn clip(d: &Drawn, (w, h): (usize, usize)) -> (usize, usize, usize, usize) { | |
| 984 | + let x0 = d.x0.clamp(0, w as i32) as usize; | |
| 985 | + let x1 = (d.x0 + d.w as i32).clamp(0, w as i32) as usize; | |
| 986 | + let y0 = d.y0.clamp(0, h as i32) as usize; | |
| 987 | + let y1 = (d.y0 + d.h as i32).clamp(0, h as i32) as usize; | |
| 988 | + (x0, y0, x1, y1) | |
| 989 | +} | |
| 990 | + | |
| 991 | +fn paint_bgra(d: &Drawn, canvas: &mut [u8], (w, h): (usize, usize), fade: u8) { | |
| 992 | + let (x0, y0, x1, y1) = clip(d, (w, h)); | |
| 993 | + for layer in &d.layers { | |
| 994 | + let [r, g, b, a] = layer.rgba; | |
| 995 | + let k = mul(a, fade); | |
| 996 | + for py in y0..y1 { | |
| 997 | + for px in x0..x1 { | |
| 998 | + let c = layer.cov[(py as i32 - d.y0) as usize * d.w + (px as i32 - d.x0) as usize]; | |
| 999 | + if c == 0 { | |
| 1000 | + continue; | |
| 1001 | + } | |
| 1002 | + let alpha = mul(c, k); | |
| 1003 | + let i = (py * w + px) * 4; | |
| 1004 | + canvas[i] = mix(canvas[i], b, alpha); | |
| 1005 | + canvas[i + 1] = mix(canvas[i + 1], g, alpha); | |
| 1006 | + canvas[i + 2] = mix(canvas[i + 2], r, alpha); | |
| 1007 | + } | |
| 1008 | + } | |
| 1009 | + } | |
| 1010 | +} | |
| 1011 | + | |
| 1012 | +fn paint_i420(d: &Drawn, planes: (&mut [u8], &mut [u8], &mut [u8]), (w, h): (usize, usize), full_range: bool, fade: u8) { | |
| 1013 | + let (yp, up, vp) = planes; | |
| 1014 | + let cw = w.div_ceil(2); | |
| 1015 | + let bt709 = !is_sd(w as u32, h as u32); | |
| 1016 | + let (x0, y0, x1, y1) = clip(d, (w, h)); | |
| 1017 | + if x0 >= x1 || y0 >= y1 { | |
| 1018 | + return; | |
| 1019 | + } | |
| 1020 | + for layer in &d.layers { | |
| 1021 | + let k = mul(layer.rgba[3], fade); | |
| 1022 | + let (yy, uu, vv) = yuv(layer.rgba, bt709, full_range); | |
| 1023 | + let alpha = |px: usize, py: usize| -> u32 { | |
| 1024 | + let c = layer.cov[(py as i32 - d.y0) as usize * d.w + (px as i32 - d.x0) as usize]; | |
| 1025 | + u32::from(mul(c, k)) | |
| 1026 | + }; | |
| 1027 | + for py in y0..y1 { | |
| 1028 | + for px in x0..x1 { | |
| 1029 | + let a = alpha(px, py) as u8; | |
| 1030 | + if a > 0 { | |
| 1031 | + let i = py * w + px; | |
| 1032 | + yp[i] = mix(yp[i], yy, a); | |
| 1033 | + } | |
| 1034 | + } | |
| 1035 | + } | |
| 1036 | + for cy in y0 / 2..=(y1 - 1) / 2 { | |
| 1037 | + for cx in x0 / 2..=(x1 - 1) / 2 { | |
| 1038 | + let (mut sa, mut su, mut sv) = (0u32, 0u32, 0u32); | |
| 1039 | + for dy in 0..2 { | |
| 1040 | + for dx in 0..2 { | |
| 1041 | + let (px, py) = (cx * 2 + dx, cy * 2 + dy); | |
| 1042 | + if (x0..x1).contains(&px) && (y0..y1).contains(&py) { | |
| 1043 | + let a = alpha(px, py); | |
| 1044 | + sa += a; | |
| 1045 | + su += a * u32::from(uu); | |
| 1046 | + sv += a * u32::from(vv); | |
| 1047 | + } | |
| 1048 | + } | |
| 1049 | + } | |
| 1050 | + if sa > 0 { | |
| 1051 | + let i = cy * cw + cx; | |
| 1052 | + let cover = (sa / 4) as u8; | |
| 1053 | + up[i] = mix(up[i], (su / sa) as u8, cover); | |
| 1054 | + vp[i] = mix(vp[i], (sv / sa) as u8, cover); | |
| 1055 | + } | |
| 1056 | + } | |
| 1057 | + } | |
| 1058 | + } | |
| 1059 | +} | |
| 1060 | + | |
| 1061 | +#[cfg(test)] | |
| 1062 | +mod tests { | |
| 1063 | + #[test] | |
| 1064 | + fn colour_is_bgr_with_a_transparency_byte() { | |
| 1065 | + assert_eq!(super::colour("&H64100908"), Some([8, 9, 16, 155])); | |
| 1066 | + } | |
| 1067 | +} |
crates/engine/src/export.rsmodified+86 -20
| @@ -3288,6 +3288,10 @@ pub fn default_export_folder(project: &Path) -> PathBuf { | ||
| 3288 | 3288 | /// Pure and cheap enough to ask per repaint (a walk of the spans and of the |
| 3289 | 3289 | /// cues, no file opened), which is how a front-end asks it. |
| 3290 | 3290 | pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> { |
| 3291 | + timeline_cues_indexed(project, track, fps).into_iter().map(|(_, cue)| cue).collect() | |
| 3292 | +} | |
| 3293 | + | |
| 3294 | +fn timeline_cues_indexed(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<(usize, Cue)> { | |
| 3291 | 3295 | let frames = project.timeline_frames(); |
| 3292 | 3296 | let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; |
| 3293 | 3297 | let end = us(frames); |
| @@ -3307,16 +3311,17 @@ pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec< | ||
| 3307 | 3311 | return track |
| 3308 | 3312 | .cues |
| 3309 | 3313 | .iter() |
| 3310 | - .filter_map(|cue| { | |
| 3314 | + .enumerate() | |
| 3315 | + .filter_map(|(i, cue)| { | |
| 3311 | 3316 | let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); |
| 3312 | - (end_us > start_us).then_some(Cue { | |
| 3317 | + (end_us > start_us).then_some((i, Cue { | |
| 3313 | 3318 | start_us, |
| 3314 | 3319 | end_us, |
| 3315 | 3320 | text: cue.text.clone(), |
| 3316 | 3321 | image: cue.image.clone(), |
| 3317 | 3322 | words: crate::subtitle::map_words(&cue.words, (start_us, end_us), (start_us, end_us)), |
| 3318 | 3323 | karaoke: crate::subtitle::map_karaoke(&cue.karaoke, (start_us, end_us), (start_us, end_us)), |
| 3319 | - }) | |
| 3324 | + })) | |
| 3320 | 3325 | }) |
| 3321 | 3326 | .collect(); |
| 3322 | 3327 | }; |
| @@ -3352,13 +3357,13 @@ pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec< | ||
| 3352 | 3357 | let frames = if hi == lo { b } else { a + (b - a) * (f - f64::from(lo)) }; |
| 3353 | 3358 | start + (frames / fps * 1e6).round() as i64 |
| 3354 | 3359 | }; |
| 3355 | - for cue in &track.cues { | |
| 3360 | + for (i, cue) in track.cues.iter().enumerate() { | |
| 3356 | 3361 | let (a, b) = (cue.start_us.max(first), cue.end_us.min(last)); |
| 3357 | 3362 | if b <= a { |
| 3358 | 3363 | continue; // wholly outside what this span kept |
| 3359 | 3364 | } |
| 3360 | 3365 | let (from, to) = if span.reverse { (last - b, last - a) } else { (a - first, b - first) }; |
| 3361 | - out.push(Cue { | |
| 3366 | + out.push((i, Cue { | |
| 3362 | 3367 | start_us: onto(from), |
| 3363 | 3368 | end_us: onto(to).min(end), |
| 3364 | 3369 | text: cue.text.clone(), |
| @@ -3389,12 +3394,12 @@ pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec< | ||
| 3389 | 3394 | }) |
| 3390 | 3395 | .collect() |
| 3391 | 3396 | }, |
| 3392 | - }); | |
| 3397 | + })); | |
| 3393 | 3398 | } |
| 3394 | 3399 | } |
| 3395 | 3400 | // The spans come in timeline order but a cue's *own* order across them does |
| 3396 | 3401 | // not: a Matroska muxer writes blocks as they come up. |
| 3397 | - out.sort_by_key(|cue| cue.start_us); | |
| 3402 | + out.sort_by_key(|(_, cue)| cue.start_us); | |
| 3398 | 3403 | out |
| 3399 | 3404 | } |
| 3400 | 3405 | |
| @@ -6289,31 +6294,35 @@ fn run( | ||
| 6289 | 6294 | /// |
| 6290 | 6295 | /// `Err` for a pick that is not a track of the project. |
| 6291 | 6296 | pub fn burn_cues(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<Cue>> { |
| 6297 | + Ok(burn_cues_indexed(project, pick, fps)?.into_iter().map(|(_, cue)| cue).collect()) | |
| 6298 | +} | |
| 6299 | + | |
| 6300 | +fn burn_cues_indexed(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<(usize, Cue)>> { | |
| 6292 | 6301 | let track = project |
| 6293 | 6302 | .subtitles() |
| 6294 | 6303 | .get(pick) |
| 6295 | 6304 | .ok_or_else(|| format!("burn_subtitles: no subtitle track {pick} in this project"))?; |
| 6296 | 6305 | if !placed_tracks(project).contains(&pick) { |
| 6297 | - return Ok(timeline_cues(project, track, fps)); | |
| 6306 | + return Ok(timeline_cues_indexed(project, track, fps)); | |
| 6298 | 6307 | } |
| 6299 | - let mut cues: Vec<Cue> = project | |
| 6308 | + let mut cues: Vec<(usize, Cue)> = project | |
| 6300 | 6309 | .subtitle_lanes() |
| 6301 | 6310 | .into_iter() |
| 6302 | 6311 | .flat_map(|lane| project.sub_lane_cue_spans(lane, fps)) |
| 6303 | 6312 | .filter(|s| s.track == pick) |
| 6304 | 6313 | .filter_map(|s| { |
| 6305 | 6314 | let c = track.cues.get(s.cue)?; |
| 6306 | - Some(Cue { | |
| 6315 | + Some((s.cue, Cue { | |
| 6307 | 6316 | start_us: s.start_us, |
| 6308 | 6317 | end_us: s.end_us, |
| 6309 | 6318 | text: c.text.clone(), |
| 6310 | 6319 | image: c.image.clone(), |
| 6311 | 6320 | words: crate::subtitle::map_words(&c.words, s.window, (s.start_us, s.end_us)), |
| 6312 | 6321 | karaoke: crate::subtitle::map_karaoke(&c.karaoke, s.window, (s.start_us, s.end_us)), |
| 6313 | - }) | |
| 6322 | + })) | |
| 6314 | 6323 | }) |
| 6315 | 6324 | .collect(); |
| 6316 | - cues.sort_by_key(|c| c.start_us); | |
| 6325 | + cues.sort_by_key(|(_, c)| c.start_us); | |
| 6317 | 6326 | Ok(cues) |
| 6318 | 6327 | } |
| 6319 | 6328 | |
| @@ -6367,6 +6376,33 @@ struct Burn { | ||
| 6367 | 6376 | titles: Vec<Title>, |
| 6368 | 6377 | /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]). |
| 6369 | 6378 | title_last: Vec<Option<(TitleKey, Overlay)>>, |
| 6379 | + native: Option<Native>, | |
| 6380 | +} | |
| 6381 | + | |
| 6382 | +struct Native { | |
| 6383 | + captions: crate::assrender::Captions, | |
| 6384 | + sources: Vec<usize>, | |
| 6385 | +} | |
| 6386 | + | |
| 6387 | +fn native_script(project: &Project, pick: usize, style: &TextStyle) -> Option<crate::assrender::Captions> { | |
| 6388 | + if !style.native { | |
| 6389 | + return None; | |
| 6390 | + } | |
| 6391 | + let track = project.subtitles().get(pick)?; | |
| 6392 | + if track.track.is_some() { | |
| 6393 | + return None; | |
| 6394 | + } | |
| 6395 | + crate::assrender::Captions::from_file(&track.path) | |
| 6396 | +} | |
| 6397 | + | |
| 6398 | +fn native_shown(cues: &[Cue], sources: &[usize], on: &[usize]) -> Vec<crate::assrender::Shown> { | |
| 6399 | + on.iter() | |
| 6400 | + .map(|&i| crate::assrender::Shown { | |
| 6401 | + event: sources[i], | |
| 6402 | + start_us: cues[i].start_us, | |
| 6403 | + end_us: cues[i].end_us, | |
| 6404 | + }) | |
| 6405 | + .collect() | |
| 6370 | 6406 | } |
| 6371 | 6407 | |
| 6372 | 6408 | /// What a title's overlay is made from: a frame's size, how much of its text shows and its |
| @@ -6423,11 +6459,13 @@ impl Burn { | ||
| 6423 | 6459 | full_range: bool, |
| 6424 | 6460 | ) -> crate::Result<Option<Self>> { |
| 6425 | 6461 | let titles = project.titles().to_vec(); |
| 6426 | - let (cues, style) = match &settings.burn_subtitles { | |
| 6462 | + let (cues, style, native) = match &settings.burn_subtitles { | |
| 6427 | 6463 | Some((pick, style)) => { |
| 6428 | - (burn_cues(project, *pick, fps)?, style.clamped()) | |
| 6464 | + let (sources, cues): (Vec<usize>, Vec<Cue>) = burn_cues_indexed(project, *pick, fps)?.into_iter().unzip(); | |
| 6465 | + let native = native_script(project, *pick, style).map(|captions| Native { captions, sources }); | |
| 6466 | + (cues, style.clamped(), native) | |
| 6429 | 6467 | } |
| 6430 | - None => (Vec::new(), TextStyle::default()), | |
| 6468 | + None => (Vec::new(), TextStyle::default(), None), | |
| 6431 | 6469 | }; |
| 6432 | 6470 | if cues.is_empty() && titles.is_empty() && settings.burn_subtitles.is_none() { |
| 6433 | 6471 | return Ok(None); |
| @@ -6440,6 +6478,7 @@ impl Burn { | ||
| 6440 | 6478 | last: None, |
| 6441 | 6479 | title_last: vec![None; titles.len()], |
| 6442 | 6480 | titles, |
| 6481 | + native, | |
| 6443 | 6482 | })) |
| 6444 | 6483 | } |
| 6445 | 6484 | |
| @@ -6486,6 +6525,24 @@ impl Burn { | ||
| 6486 | 6525 | out = Some(planes); |
| 6487 | 6526 | } |
| 6488 | 6527 | let on = cues_on_screen(&self.cues, frame, self.fps); |
| 6528 | + if let Some(native) = self.native.as_mut() { | |
| 6529 | + if !on.is_empty() { | |
| 6530 | + let shown = native_shown(&self.cues, &native.sources, &on); | |
| 6531 | + let t_us = (f64::from(frame) / self.fps * 1e6).round() as i64; | |
| 6532 | + let mut planes = out | |
| 6533 | + .take() | |
| 6534 | + .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec())); | |
| 6535 | + native.captions.draw_i420( | |
| 6536 | + (&mut planes.0, &mut planes.1, &mut planes.2), | |
| 6537 | + (width, height), | |
| 6538 | + self.full_range, | |
| 6539 | + &shown, | |
| 6540 | + t_us, | |
| 6541 | + ); | |
| 6542 | + out = Some(planes); | |
| 6543 | + } | |
| 6544 | + return out; | |
| 6545 | + } | |
| 6489 | 6546 | if !on.is_empty() { |
| 6490 | 6547 | // A static style is keyed by the cues alone, so a cache hit builds nothing. |
| 6491 | 6548 | // A karaoke cue moves with the clock whatever the style, so it is planned too. |
| @@ -6996,12 +7053,20 @@ pub fn compose_at_with( | ||
| 6996 | 7053 | } |
| 6997 | 7054 | } |
| 6998 | 7055 | if let Some((pick, style)) = burn { |
| 6999 | - let cues = burn_cues(project, pick, meta.frame_rate)?; | |
| 7056 | + let (sources, cues): (Vec<usize>, Vec<Cue>) = burn_cues_indexed(project, pick, meta.frame_rate)?.into_iter().unzip(); | |
| 7000 | 7057 | let on = cues_on_screen(&cues, frame, meta.frame_rate); |
| 7001 | - if !on.is_empty() { | |
| 7002 | - let style = style.clamped(); | |
| 7003 | - let blocks = crate::captionanim::plan(&style, &cues, &on, frame, meta.frame_rate); | |
| 7004 | - overlay_blocks(&style, tw, th, &blocks).blend_bgra(&mut bgra); | |
| 7058 | + match native_script(project, pick, &style) { | |
| 7059 | + Some(mut captions) => { | |
| 7060 | + let shown = native_shown(&cues, &sources, &on); | |
| 7061 | + let t_us = (f64::from(frame) / meta.frame_rate * 1e6).round() as i64; | |
| 7062 | + captions.draw_bgra(&mut bgra, (tw, th), &shown, t_us); | |
| 7063 | + } | |
| 7064 | + None if !on.is_empty() => { | |
| 7065 | + let style = style.clamped(); | |
| 7066 | + let blocks = crate::captionanim::plan(&style, &cues, &on, frame, meta.frame_rate); | |
| 7067 | + overlay_blocks(&style, tw, th, &blocks).blend_bgra(&mut bgra); | |
| 7068 | + } | |
| 7069 | + None => {} | |
| 7005 | 7070 | } |
| 7006 | 7071 | } |
| 7007 | 7072 | Ok(crate::decode::Frame { |
| @@ -11900,6 +11965,7 @@ mod burn_stack_tests { | ||
| 11900 | 11965 | last: None, |
| 11901 | 11966 | titles: Vec::new(), |
| 11902 | 11967 | title_last: Vec::new(), |
| 11968 | + native: None, | |
| 11903 | 11969 | }; |
| 11904 | 11970 | let y = vec![40u8; (w * h) as usize]; |
| 11905 | 11971 | let u = vec![128u8; (w / 2 * (h / 2)) as usize]; |
crates/engine/src/lib.rsmodified+1 -0
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | #![forbid(unsafe_code)] |
| 4 | 4 | |
| 5 | 5 | pub mod ao; |
| 6 | +pub mod assrender; | |
| 6 | 7 | pub mod auto_color; |
| 7 | 8 | pub mod audio; |
| 8 | 9 | pub mod caps; |
crates/engine/src/text.rsmodified+22 -3
| @@ -168,6 +168,22 @@ fn face_k() -> &'static [f32; OUTLINE_FACES] { | ||
| 168 | 168 | pub(crate) struct Family { |
| 169 | 169 | font: &'static FontRef<'static>, |
| 170 | 170 | k: f32, |
| 171 | + /// The font file's bytes and the face index in them, for the OS/2 metrics. | |
| 172 | + data: &'static [u8], | |
| 173 | + index: u32, | |
| 174 | +} | |
| 175 | + | |
| 176 | +impl Family { | |
| 177 | + /// The glyph font, the bytes it was read from and the face index in them. | |
| 178 | + pub(crate) fn parts(&self) -> (&'static FontRef<'static>, &'static [u8], u32) { | |
| 179 | + (self.font, self.data, self.index) | |
| 180 | + } | |
| 181 | +} | |
| 182 | + | |
| 183 | +/// The bundled Archivo face, Bold or Medium, as a [`Family`]. | |
| 184 | +pub(crate) fn bundled_family(bold: bool) -> Option<Family> { | |
| 185 | + let i = if bold { ARCHIVO_BOLD } else { ARCHIVO }; | |
| 186 | + Some(Family { font: outline_face(i)?, k: 1.0, data: OUTLINE_BYTES[i], index: 0 }) | |
| 171 | 187 | } |
| 172 | 188 | |
| 173 | 189 | /// The scale that sets a system face's height and x-height to Archivo's. |
| @@ -212,7 +228,7 @@ pub(crate) fn family_face(name: &str) -> Option<Family> { | ||
| 212 | 228 | let data: &'static [u8] = Box::leak(data.to_vec().into_boxed_slice()); |
| 213 | 229 | let font = FontRef::try_from_slice_and_index(data, index).ok()?; |
| 214 | 230 | let k = family_k(&font, data, index); |
| 215 | - Some(Family { font: Box::leak(Box::new(font)), k }) | |
| 231 | + Some(Family { font: Box::leak(Box::new(font)), k, data, index }) | |
| 216 | 232 | }) |
| 217 | 233 | .flatten() |
| 218 | 234 | }) |
| @@ -367,6 +383,8 @@ pub struct TextStyle { | ||
| 367 | 383 | /// How a burned caption is animated against its word times. Only the |
| 368 | 384 | /// caption path ([`crate::captionanim::plan`]) reads it; a title ignores it. |
| 369 | 385 | pub caption: crate::captionanim::CaptionStyle, |
| 386 | + /// A burned ASS file is drawn as its script says ([`crate::assrender`]) when true. | |
| 387 | + pub native: bool, | |
| 370 | 388 | } |
| 371 | 389 | |
| 372 | 390 | impl Default for TextStyle { |
| @@ -383,6 +401,7 @@ impl Default for TextStyle { | ||
| 383 | 401 | box_color: [0, 0, 0, BOX_ALPHA], |
| 384 | 402 | family: None, |
| 385 | 403 | caption: crate::captionanim::CaptionStyle::default(), |
| 404 | + native: true, | |
| 386 | 405 | } |
| 387 | 406 | } |
| 388 | 407 | } |
| @@ -716,14 +735,14 @@ impl Overlay { | ||
| 716 | 735 | } |
| 717 | 736 | |
| 718 | 737 | /// `dst` pulled toward `src` by `a / 255`. |
| 719 | -fn mix(dst: u8, src: u8, a: u8) -> u8 { | |
| 738 | +pub(crate) fn mix(dst: u8, src: u8, a: u8) -> u8 { | |
| 720 | 739 | let a = u32::from(a); |
| 721 | 740 | ((u32::from(dst) * (255 - a) + u32::from(src) * a + 127) / 255) as u8 |
| 722 | 741 | } |
| 723 | 742 | |
| 724 | 743 | /// The Y, Cb and Cr of a colour in the matrix (BT.709 or BT.601) and range a frame |
| 725 | 744 | /// is coded in: full range spans 0 to 255, limited range 16 to 235 and 16 to 240. |
| 726 | -fn yuv(c: [u8; 4], bt709: bool, full_range: bool) -> (u8, u8, u8) { | |
| 745 | +pub(crate) fn yuv(c: [u8; 4], bt709: bool, full_range: bool) -> (u8, u8, u8) { | |
| 727 | 746 | let (kr, kb) = if bt709 { |
| 728 | 747 | (0.2126, 0.0722) |
| 729 | 748 | } else { |
crates/mcp/src/tools/export.rsmodified+10 -3
| @@ -20,9 +20,9 @@ const FINISHED_LISTED: usize = 5; | ||
| 20 | 20 | |
| 21 | 21 | /// The argument key of burned-in captions, shared with `frame` and `contact_sheet`. |
| 22 | 22 | pub(crate) const BURN_KEY: &str = "burn_captions"; |
| 23 | -const BURN_KEYS: [&str; 11] = ["track", "size", "outline", "boxed", "place", "family", "animation", "highlight", "box", "uppercase", "words_per_line"]; | |
| 23 | +const BURN_KEYS: [&str; 12] = ["track", "size", "outline", "boxed", "place", "family", "animation", "highlight", "box", "uppercase", "words_per_line", "native"]; | |
| 24 | 24 | const BURN_DOC: &str = "Draw one subtitle track's text into the picture, so it shows in every \ |
| 25 | -player and in WebM. Text cues only: a bitmap track (PGS) is refused. Compare `subtitles`, which \ | |
| 25 | +player and in WebM. Text cues only: a bitmap track (PGS) is refused. An .ass track is drawn as its script says unless native is false. Compare `subtitles`, which \ | |
| 26 | 26 | adds soft tracks a player can switch off; WebM carries no soft subtitles, so burn there. \ |
| 27 | 27 | One track only: two speakers' captions burn together when they share a track, which auto_captions makes by merging a second speaker into the same caption lane (auto_captions {target:\"A2\", lane:\"S1\"})."; |
| 28 | 28 | |
| @@ -849,6 +849,10 @@ pub(crate) fn burn_schema() -> Value { | ||
| 849 | 849 | "minimum": 0, |
| 850 | 850 | "maximum": 12, |
| 851 | 851 | "description": "At most this many words on screen at once; a longer cue is re-chunked by its word times (2 to 4 is the shorts style). 0 keeps each cue whole (default). The word animation is always one." |
| 852 | + }, | |
| 853 | + "native": { | |
| 854 | + "type": "boolean", | |
| 855 | + "description": "A track that is an .ass or .ssa file is drawn as its script says: its styles, positions, outline, shadow and fades. false draws it with the caption options above instead. Default true; other tracks ignore it." | |
| 852 | 856 | } |
| 853 | 857 | }, |
| 854 | 858 | "additionalProperties": false |
| @@ -886,7 +890,7 @@ pub(crate) fn parse_burn(args: &Value, s: &PlaybackSession) -> Result<Option<(us | ||
| 886 | 890 | .ok_or("burn_captions must be an object or a boolean, e.g. {\"track\": 0, \"size\": 50} or true")?; |
| 887 | 891 | if let Some(key) = obj.keys().find(|k| !BURN_KEYS.contains(&k.as_str())) { |
| 888 | 892 | return Err(format!( |
| 889 | - "burn_captions: unknown key `{key}`: the keys are track, size, outline, boxed, place, family, animation, highlight, box, uppercase, words_per_line" | |
| 893 | + "burn_captions: unknown key `{key}`: the keys are track, size, outline, boxed, place, family, animation, highlight, box, uppercase, words_per_line, native" | |
| 890 | 894 | )); |
| 891 | 895 | } |
| 892 | 896 | let subs = s.subtitles(); |
| @@ -956,6 +960,9 @@ pub(crate) fn parse_burn(args: &Value, s: &PlaybackSession) -> Result<Option<(us | ||
| 956 | 960 | if let Some(v) = obj.get("boxed").filter(|v| !v.is_null()) { |
| 957 | 961 | style.boxed = v.as_bool().ok_or("burn_captions.boxed must be true or false")?; |
| 958 | 962 | } |
| 963 | + if let Some(v) = obj.get("native").filter(|v| !v.is_null()) { | |
| 964 | + style.native = v.as_bool().ok_or("burn_captions.native must be true or false")?; | |
| 965 | + } | |
| 959 | 966 | if let Some(v) = obj.get("place").filter(|v| !v.is_null()) { |
| 960 | 967 | style.place = match v.as_str() { |
| 961 | 968 | Some("bottom") => Place::Bottom, |