Skip to content

programmatic video rendering framework that is actually fast

feat(captions): reusable VTT and JSON captions with lazy typed metadata (#251)

Dmitriy Kovalenkod1a8d45896b3
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml
index a1574f8a..547e1e35 100644
--- a/.github/workflows/main.yml
+++ b/.github/workflows/main.yml
@@ -93,6 +93,10 @@ jobs:
working-directory: fframes-editor
run: pnpm build
+ - name: Media loading regression test
+ working-directory: fframes-editor
+ run: node --test tests/media-loader.test.mjs
+
build-rust:
name: Build and Test
continue-on-error: true
@@ -265,7 +269,7 @@ jobs:
env:
RUSTFLAGS: --cfg fframes_docsrs
RUSTDOCFLAGS: --cfg docsrs -D warnings
- run: cargo doc --no-deps -p fframes-media -p fframes --features fframes/cli,fframes/compile-time-svgtree,fframes/exif,fframes/3d
+ run: cargo doc --no-deps -p fframes-media -p fframes --features fframes/cli,fframes/captions,fframes/compile-time-svgtree,fframes/exif,fframes/3d
release:
# A push to main publishes a nightly, a v* tag publishes that version (scripts/release-version.sh)
@@ -358,7 +362,7 @@ jobs:
cargo clippy $PACKAGES --tests -- -D warnings
- name: Unit tests
- run: cargo test -p fframes -p fframes-media -p webvtt-parser -p fframes-media-dir-macro
+ run: cargo test -p fframes -p fframes-media -p webvtt-parser -p fframes-media-dir-macro --features fframes/captions
- name: Render a video
run: cargo test -p e2e-tests --test render_smoke -- --nocapture
diff --git a/Cargo.lock b/Cargo.lock
index 1b778ddd..2b0fff32 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -507,6 +507,15 @@ dependencies = [
"wayland-client",
]
+[[package]]
+name = "captions-example"
+version = "1.3.0"
+dependencies = [
+ "fframes",
+ "fframes_skia_renderer",
+ "serde",
+]
+
[[package]]
name = "cargo-fframes"
version = "1.3.0"
@@ -1271,6 +1280,8 @@ dependencies = [
"libc",
"log",
"quote",
+ "serde",
+ "serde_json",
"ttf-parser",
"usvgr",
"wasm-bindgen",
diff --git a/Cargo.toml b/Cargo.toml
index 074a424c..54ae18a1 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,6 +17,7 @@ members = [
"render-bench/vs-remotion",
"cargo-fframes",
# Examples
+ "examples/captions",
"examples/podcast",
"examples/podcast/editor/editor-bridge",
"examples/audio-announce",
diff --git a/README.md b/README.md
index 54f25130..f220973e 100644
--- a/README.md
+++ b/README.md
@@ -151,13 +151,13 @@ impl Video for HelloWorldVideo<'_> {
The skill's guides are plain Markdown, so you can read them too:
[the workflow](skills/fframes-video/SKILL.md), [the API cheat sheet](skills/fframes-video/references/api.md),
+[captions](skills/fframes-video/references/captions.md),
[design](skills/fframes-video/references/design.md) and [sound](skills/fframes-video/references/audio.md).
The full API reference is on [docs.rs/fframes](https://docs.rs/fframes).
## Examples
-Click a poster to watch the video, or an example name to browse its source. Each example's README also has
-the video inline.
+Click an example name to browse its source, or a poster for a preview.
- [Motion and launch videos](#motion-and-launch-videos)
- [Shaders and 3D](#shaders-and-3d)
@@ -257,6 +257,14 @@ An svgr UI on the screen of a turning 3D monitor, showing a 3D cube with the svg
### Audio and video
+#### [captions](examples/captions)
+
+A small example of Highlight, Karaoke, Reveal and Word modes sharing one JSON transcript. Typed per-word metadata adds circles and underlines without registration or per-frame parsing. Run with `cargo run --release -p captions-example -- render`.
+
+<a href="examples/_previews/captions.png">
+ <img alt="Caption presets and custom word highlights" src="examples/_previews/captions.png" width="640" />
+</a>
+
#### [audio-announce](examples/audio-announce)
An automated workflow to create audio visualisation with automated subtitles.
diff --git a/e2e/snapshots/captions/1.5s.png b/e2e/snapshots/captions/1.5s.png
new file mode 100644
index 00000000..cc011384
Binary files /dev/null and b/e2e/snapshots/captions/1.5s.png differ
diff --git a/e2e/snapshots/captions/5.2s.png b/e2e/snapshots/captions/5.2s.png
new file mode 100644
index 00000000..bd5b28b5
Binary files /dev/null and b/e2e/snapshots/captions/5.2s.png differ
diff --git a/e2e/snapshots/captions/7s.png b/e2e/snapshots/captions/7s.png
new file mode 100644
index 00000000..05f022d6
Binary files /dev/null and b/e2e/snapshots/captions/7s.png differ
diff --git a/examples/_previews/captions.png b/examples/_previews/captions.png
new file mode 100644
index 00000000..cc011384
Binary files /dev/null and b/examples/_previews/captions.png differ
diff --git a/examples/captions/Cargo.toml b/examples/captions/Cargo.toml
new file mode 100644
index 00000000..99d9b317
--- /dev/null
+++ b/examples/captions/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "captions-example"
+version = "1.3.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+fframes = { workspace = true, features = ["cli", "captions", "compile-time-svgtree"] }
+serde = { version = "1", features = ["derive"] }
+
+[features]
+default = ["skia"]
+skia = ["dep:fframes_skia_renderer"]
+
+[target.'cfg(target_os = "macos")'.dependencies]
+fframes_skia_renderer = { workspace = true, optional = true, features = ["cli", "metal"] }
+
+[target.'cfg(not(any(target_os = "macos", target_arch = "wasm32")))'.dependencies]
+fframes_skia_renderer = { workspace = true, optional = true, features = ["cli", "vulkan"] }
+
+[target.'cfg(not(any(windows, target_arch = "wasm32")))'.dependencies]
+fframes = { workspace = true, features = ["h264", "libav-agree-gpl", "build-portable"] }
+
+[lints]
+workspace = true
diff --git a/examples/captions/media/DMSans-Medium.ttf b/examples/captions/media/DMSans-Medium.ttf
new file mode 100644
index 00000000..fc8a5ebd
Binary files /dev/null and b/examples/captions/media/DMSans-Medium.ttf differ
diff --git a/examples/captions/media/speech.json b/examples/captions/media/speech.json
new file mode 100644
index 00000000..d6834956
--- /dev/null
+++ b/examples/captions/media/speech.json
@@ -0,0 +1,30 @@
+{
+ "cues": [
+ {
+ "start": 0, "end": 3.6,
+ "words": [
+ {"text": "One", "start": 0, "end": 0.5},
+ {"text": "track,", "start": 0.5, "end": 1.2, "metadata": {"effect": "underline", "color": "#77e6cf"}},
+ {"text": "four", "start": 1.2, "end": 2.1, "metadata": {"effect": "circle", "color": "#f0bc78"}},
+ {"text": "ways", "start": 2.1, "end": 2.8},
+ {"text": "to", "start": 2.8, "end": 3.1},
+ {"text": "read.", "start": 3.1, "end": 3.6}
+ ]
+ },
+ {
+ "start": 4, "end": 7.6,
+ "words": [
+ {"text": "Highlight", "start": 4, "end": 4.6},
+ {"text": "the", "start": 4.6, "end": 4.9},
+ {"text": "words", "start": 4.9, "end": 5.5, "metadata": {"effect": "underline", "color": "#77e6cf"}},
+ {"text": "that", "start": 5.5, "end": 6},
+ {"text": "matter.", "start": 6, "end": 6.8, "metadata": {"effect": "circle", "color": "#f0bc78"}}
+ ]
+ },
+ {
+ "speaker": "Second speaker",
+ "start": 6.8, "end": 7.6,
+ "text": "Keep both voices visible."
+ }
+ ]
+}
diff --git a/examples/captions/src/lib.rs b/examples/captions/src/lib.rs
new file mode 100644
index 00000000..3ba205e1
--- /dev/null
+++ b/examples/captions/src/lib.rs
@@ -0,0 +1,92 @@
+//! A small captions example: one media track, four presets and a typed word highlight.
+use fframes::captions::{CaptionMode, CaptionRect, Captions};
+use fframes::{AudioMap, Duration, FFramesContext, Frame, Svgr, Video, include_media_dir, svgr};
+
+include_media_dir!(pub struct CaptionMedia, "examples/captions/media");
+
+#[derive(serde::Deserialize)]
+#[serde(tag = "effect", rename_all = "kebab-case")]
+enum Highlight {
+ Underline { color: String },
+ Circle { color: String },
+}
+
+pub struct CaptionVideo {
+ modes: [Captions; 4],
+}
+
+impl Default for CaptionVideo {
+ fn default() -> Self {
+ Self {
+ modes: [
+ (CaptionMode::Highlight, 90.0, 230.0),
+ (CaptionMode::Karaoke, 1010.0, 230.0),
+ (CaptionMode::Reveal, 90.0, 660.0),
+ (CaptionMode::Word, 1010.0, 660.0),
+ ]
+ .map(|(mode, x, y)| {
+ Captions::from_media("speech.json", CaptionRect::new(x, y, 820.0, 240.0))
+ .font("DM Sans", 58)
+ .font_weight(500)
+ .mode(mode)
+ .active_fill("#77e6cf")
+ .upcoming_fill("#64748b")
+ .outline("#0c1423", 2.0)
+ }),
+ }
+ }
+}
+
+impl Video for CaptionVideo {
+ const FPS: usize = 30;
+ const WIDTH: usize = 1920;
+ const HEIGHT: usize = 1080;
+
+ fn duration(&self) -> Duration<'_> {
+ Duration::Seconds(8.0)
+ }
+
+ fn audio(&self) -> AudioMap<'_> {
+ AudioMap::none()
+ }
+
+ fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {
+ // Native, embedded and browser loading use the same cached metadata.
+ // Each type decodes only on first access; no registration or per-frame JSON parse.
+ let highlight = self.modes[0].highlight_with(&mut frame, ctx, |word, text| {
+ let decoration = match word.word.metadata.typed::<Highlight>() {
+ Some(Highlight::Underline { color }) => svgr!(
+ <path d={format!("M 0 {} H {}", word.height() - 3.0, word.width())}
+ stroke={color.as_str()} stroke-width="4" stroke-linecap="round" />
+ ),
+ Some(Highlight::Circle { color }) => svgr!(
+ <ellipse cx={word.width() / 2.0} cy={word.height() / 2.0}
+ rx={word.width() / 2.0 + 10.0} ry={word.height() / 2.0 + 5.0}
+ fill="none" stroke={color.as_str()} stroke-width="3" />
+ ),
+ None => Svgr::empty(),
+ };
+ // The scope is borrowed and text is owned: neither needs cloning.
+ svgr!(<g>{decoration}{text}</g>)
+ });
+ let karaoke = self.modes[1].render(&mut frame, ctx);
+ let reveal = self.modes[2].render(&mut frame, ctx);
+ let word = self.modes[3].render(&mut frame, ctx);
+ svgr!(
+ <svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">
+ <rect width="1920" height="1080" fill="#0c1423" />
+ <path d="M 960 180 V 980 M 70 570 H 1850" stroke="#253248" stroke-width="2" />
+ <g font-family="DM Sans" font-weight="500" fill="#f4f7fb">
+ <text x="90" y="110" font-size="54">"One transcript, four treatments"</text>
+ <g font-size="26" fill="#91a3b9">
+ <text x="90" y="210">"HIGHLIGHT + TYPED WORD EFFECTS"</text>
+ <text x="1010" y="210">"KARAOKE"</text>
+ <text x="90" y="640">"REVEAL"</text>
+ <text x="1010" y="640">"WORD"</text>
+ </g>
+ </g>
+ {highlight}{karaoke}{reveal}{word}
+ </svg>
+ )
+ }
+}
diff --git a/examples/captions/src/main.rs b/examples/captions/src/main.rs
new file mode 100644
index 00000000..3f48b6d6
--- /dev/null
+++ b/examples/captions/src/main.rs
@@ -0,0 +1,24 @@
+use captions_example::{CaptionMedia, CaptionVideo};
+use fframes::{RenderOptions, cli};
+use std::process::ExitCode;
+
+fn main() -> ExitCode {
+ let media = match CaptionMedia::new() {
+ Ok(media) => media,
+ Err(error) => {
+ eprintln!("{error}");
+ return ExitCode::FAILURE;
+ }
+ };
+ let video = CaptionVideo::default();
+ let runner = cli::new(
+ &video,
+ RenderOptions {
+ media: Some(&media),
+ ..Default::default()
+ },
+ );
+ #[cfg(feature = "skia")]
+ let runner = runner.renderers(fframes_skia_renderer::cli::SkiaRenderers::default());
+ runner.run()
+}
diff --git a/fframes-editor-controller/Cargo.toml b/fframes-editor-controller/Cargo.toml
index 225ed592..8aaa847a 100644
--- a/fframes-editor-controller/Cargo.toml
+++ b/fframes-editor-controller/Cargo.toml
@@ -22,6 +22,8 @@ fframes = { workspace = true }
getrandom = { version = "0.2.15", features = ["js"] }
[features]
+# Optional SVG word-caption renderer; subtitle parsing is always available.
+captions = ["fframes/captions"]
# Lottie `.json` files of the dynamic media folder (`fframes/lottie`)
lottie = ["fframes/lottie"]
diff --git a/fframes-editor-controller/src/impl_wasm_bridge_macro.rs b/fframes-editor-controller/src/impl_wasm_bridge_macro.rs
index aaf3d199..c37a928f 100644
--- a/fframes-editor-controller/src/impl_wasm_bridge_macro.rs
+++ b/fframes-editor-controller/src/impl_wasm_bridge_macro.rs
@@ -61,10 +61,23 @@ macro_rules! internal_impl_wasm_bridge {
}
#[wasm_bindgen]
- pub fn add_subtitles_source(&self, file: String, content: String) -> usize {
+ pub fn add_subtitles_source(
+ &self,
+ file: String,
+ content: String,
+ ) -> Result<usize, JsValue> {
self.0.add_subtitles_source(file, content)
}
+ #[wasm_bindgen]
+ pub fn add_json_subtitles_source(
+ &self,
+ file: String,
+ content: String,
+ ) -> Result<Option<usize>, JsValue> {
+ self.0.add_json_subtitles_source(file, content)
+ }
+
#[wasm_bindgen]
pub fn add_lottie_source(&self, file: String, content: String) -> Option<f32> {
self.0.add_lottie_source(file, content)
diff --git a/fframes-editor-controller/src/wasm_editor.rs b/fframes-editor-controller/src/wasm_editor.rs
index a217f736..fe16f6d6 100644
--- a/fframes-editor-controller/src/wasm_editor.rs
+++ b/fframes-editor-controller/src/wasm_editor.rs
@@ -89,14 +89,21 @@ pub struct WasmEditor<T: Video, TMedia: StaticMediaProvider<'static> + 'static>
impl<TVideo: Video, TMedia: StaticMediaProvider<'static> + 'static> WasmEditor<TVideo, TMedia> {
pub fn new(video: TVideo, static_media: &'static TMedia) -> Self {
fframes::set_video_frame_resolver(resolve_video_frame);
- #[cfg(not(feature = "lottie"))]
let media_provider = fframes::DynamicMediaProvider::default();
// `render_frame` reads media from this provider. The static animations go into it too.
#[cfg(feature = "lottie")]
- let media_provider = static_media.get_all_lottie_data().into_iter().fold(
- fframes::DynamicMediaProvider::default(),
- |provider, (lottie, name)| provider.with_lottie(name, lottie.clone()),
- );
+ let media_provider = static_media
+ .get_all_lottie_data()
+ .into_iter()
+ .fold(media_provider, |provider, (lottie, name)| {
+ provider.with_lottie(name, lottie.clone())
+ });
+ let media_provider = static_media
+ .get_all_subtitle_data()
+ .into_iter()
+ .fold(media_provider, |provider, (subtitles, name)| {
+ provider.with_subtitles(name, subtitles.clone())
+ });
Self {
video_ctx: RefCell::new(VideoCtx::new(video)),
@@ -178,10 +185,12 @@ impl<TVideo: Video, TMedia: StaticMediaProvider<'static> + 'static> WasmEditor<T
.insert(file.clone(), fframes::AudioData::Preloaded(audio_data));
}
- pub fn add_subtitles_source(&self, file: String, content: String) -> usize {
+ /// Parse VTT or JSON through the shared subtitle parser and register the owned result.
+ pub fn add_subtitles_source(&self, file: String, content: String) -> Result<usize, JsValue> {
use fframes::media::FFramesSubtitles;
- let parsed_subtitle = fframes::media::Subtitles::parse(&content).unwrap();
+ let parsed_subtitle = fframes::media::CaptionTrack::parse(&content)
+ .map_err(|error| JsValue::from_str(&format!("{file}: {error}")))?;
let phrases_count = (&parsed_subtitle).cues_count();
self.media_provider
@@ -190,7 +199,41 @@ impl<TVideo: Video, TMedia: StaticMediaProvider<'static> + 'static> WasmEditor<T
.subtitles
.insert(file, parsed_subtitle);
- phrases_count
+ Ok(phrases_count)
+ }
+
+ /// Classify and retain subtitle JSON in one parse. Other JSON returns `None` for Lottie.
+ pub fn add_json_subtitles_source(
+ &self,
+ file: String,
+ content: String,
+ ) -> Result<Option<usize>, JsValue> {
+ let lower_file = file.to_ascii_lowercase();
+ let named = lower_file == "subtitles.json"
+ || lower_file == "captions.json"
+ || lower_file.ends_with(".subtitles.json")
+ || lower_file.ends_with(".captions.json");
+ let track = match fframes::media::Subtitles::parse_json_document(&content) {
+ Ok(track) => track,
+ Err(fframes::media::CaptionError::Json(error))
+ if !named && (error.is_syntax() || error.is_eof()) =>
+ {
+ // Match native loading: unrelated malformed JSON can still take
+ // the Lottie path, which reports it without aborting media loading.
+ return Ok(None);
+ }
+ Err(error) => return Err(JsValue::from_str(&format!("{file}: {error}"))),
+ };
+ let Some(track) = track else {
+ return Ok(None);
+ };
+ let count = track.cues().len();
+ self.media_provider
+ .lock()
+ .unwrap()
+ .subtitles
+ .insert(file, track);
+ Ok(Some(count))
}
/// Parses a Lottie file of the dynamic media folder and returns its length in seconds.
diff --git a/fframes-editor/src/WasmController.gen.tsx b/fframes-editor/src/WasmController.gen.tsx
index a1a0383c..14f813bb 100644
--- a/fframes-editor/src/WasmController.gen.tsx
+++ b/fframes-editor/src/WasmController.gen.tsx
@@ -93,6 +93,7 @@ export type t = {
readonly add_image_source: (_1:string, _2:string, _3:number, _4:number, _5:ReScriptJs_Js_Undefined_t<string>) => void;
readonly add_video_source_placeholder: (_1:string, _2:string, _3:number, _4:number, _5:number) => void;
readonly add_subtitles_source: (_1:string, _2:string) => number;
+ readonly add_json_subtitles_source: (_1:string, _2:string) => ReScriptJs_Js_Undefined_t<number>;
readonly add_lottie_source: (_1:string, _2:string) => ReScriptJs_Js_Undefined_t<number>;
readonly prepare: (_1:ReScriptJs_Js_Undefined_t<number>) => ReScriptJs_Js_Promise_t<videoMeta>;
readonly render_frame: (_1:ReScriptJs_Js_BigInt_t) => string;
diff --git a/fframes-editor/src/WasmController.res b/fframes-editor/src/WasmController.res
index 2a89b3bf..a4ba5295 100644
--- a/fframes-editor/src/WasmController.res
+++ b/fframes-editor/src/WasmController.res
@@ -61,6 +61,7 @@ type t = {
add_image_source: (string, string, int, int, Js.Undefined.t<string>) => unit,
add_video_source_placeholder: (string, string, int, int, int) => unit,
add_subtitles_source: (string, string) => int,
+ add_json_subtitles_source: (string, string) => Js.Undefined.t<int>,
add_lottie_source: (string, string) => Js.Undefined.t<float>,
prepare: Js.Undefined.t<int> => Js.Promise.t<videoMeta>,
render_frame: Js.BigInt.t => string,
@@ -88,6 +89,9 @@ external add_video_source_placeholder: (t, string, string, int, int, int) => uni
@send @genType
external add_subtitles_source: (t, string, string) => int = "add_subtitles_source"
+@send @genType
+external add_json_subtitles_source: (t, string, string) => Js.Undefined.t<int> = "add_json_subtitles_source"
+
@send @genType
external add_lottie_source: (t, string, string) => Js.Undefined.t<float> = "add_lottie_source"
diff --git a/fframes-editor/src/services/AnimationRuntime.bs.js b/fframes-editor/src/services/AnimationRuntime.bs.js
index e8653d8e..8aed9d3c 100644
--- a/fframes-editor/src/services/AnimationRuntime.bs.js
+++ b/fframes-editor/src/services/AnimationRuntime.bs.js
@@ -93,7 +93,7 @@ function connectAudioFiles(ctx, videoMeta) {
switch (media.TAG | 0) {
case /* Media */1 :
var media$1 = media._0;
- if (media$1.TAG === /* Audio */3) {
+ if (media$1.TAG === /* Audio */4) {
return [
track,
media$1._0
diff --git a/fframes-editor/src/services/MediaResolvers.ts b/fframes-editor/src/services/MediaResolvers.ts
index 9be314f1..0a67739b 100644
--- a/fframes-editor/src/services/MediaResolvers.ts
+++ b/fframes-editor/src/services/MediaResolvers.ts
@@ -7,6 +7,9 @@ import { fontInfo } from "src/WasmController.gen";
import { Input, UrlSource, ALL_FORMATS } from "mediabunny";
import { registerVideo } from "./VideoFrameBufferManager";
+export const mediaErrorMessage = (error: unknown): string =>
+ error instanceof Error ? error.message : String(error);
+
interface VideoMetadata {
width: number;
height: number;
@@ -134,10 +137,13 @@ export const resolveSubtitles: MediaResolver = async ({
wasmController,
}) => {
const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(
+ `Unable to load subtitle media ${name}: HTTP ${response.status}`
+ );
+ }
const text = await response.text();
- let phrasesCount = 0;
-
- wasmController.add_subtitles_source(name, text);
+ const phrasesCount = wasmController.add_subtitles_source(name, text);
return resolveMedia(name, {
tag: "Subtitles",
@@ -145,13 +151,31 @@ export const resolveSubtitles: MediaResolver = async ({
});
};
-export const resolveLottie: MediaResolver = async ({
+export const resolveJson: MediaResolver = async ({
name,
url,
wasmController,
}) => {
const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(
+ `Unable to load JSON media ${name}: HTTP ${response.status}`
+ );
+ }
const text = await response.text();
+ const lowerName = name.toLowerCase();
+ const subtitleJson =
+ lowerName === "subtitles.json" ||
+ lowerName === "captions.json" ||
+ lowerName.endsWith(".subtitles.json") ||
+ lowerName.endsWith(".captions.json");
+ // Rust classifies and retains subtitle JSON in one pass, including its metadata.
+ const count = subtitleJson
+ ? wasmController.add_subtitles_source(name, text)
+ : wasmController.add_json_subtitles_source(name, text);
+ if (count !== undefined) {
+ return resolveMedia(name, { tag: "Subtitles", value: count });
+ }
const duration = wasmController.add_lottie_source(name, text);
return resolveMedia(name, {
diff --git a/fframes-editor/src/services/mediaLoader.bs.js b/fframes-editor/src/services/mediaLoader.bs.js
index 22aa13f7..7b018767 100644
--- a/fframes-editor/src/services/mediaLoader.bs.js
+++ b/fframes-editor/src/services/mediaLoader.bs.js
@@ -21,42 +21,56 @@ function reducer(state, action) {
mediaList: state.mediaList
};
}
- if (action.TAG === /* InitMediaProcessing */0) {
- return {
- allMediaLoaded: state.allMediaLoaded,
- mediaList: Belt_MapString.merge(state.mediaList, Belt_MapString.fromArray(Belt_Array.map(Object.keys(action._0), (function (relativePath) {
- return [
- Utils.Path.getFilename(relativePath),
- {
- TAG: /* Loading */0,
- _0: relativePath
- }
- ];
- }))), (function (param, staticVal, dynamicVal) {
- if (staticVal !== undefined) {
- if (dynamicVal !== undefined) {
- return dynamicVal;
- } else {
- return staticVal;
- }
- } else if (dynamicVal !== undefined) {
- return dynamicVal;
- } else {
- return ;
- }
- }))
- };
+ switch (action.TAG | 0) {
+ case /* InitMediaProcessing */0 :
+ return {
+ allMediaLoaded: false,
+ mediaList: Belt_MapString.merge(state.mediaList, Belt_MapString.fromArray(Belt_Array.map(Object.keys(action._0), (function (relativePath) {
+ return [
+ Utils.Path.getFilename(relativePath),
+ {
+ TAG: /* Loading */0,
+ _0: relativePath
+ }
+ ];
+ }))), (function (param, staticVal, dynamicVal) {
+ if (staticVal !== undefined) {
+ if (dynamicVal !== undefined) {
+ return dynamicVal;
+ } else {
+ return staticVal;
+ }
+ } else if (dynamicVal !== undefined) {
+ return dynamicVal;
+ } else {
+ return ;
+ }
+ }))
+ };
+ case /* MediaItemProcessed */1 :
+ var media = action._1;
+ return {
+ allMediaLoaded: state.allMediaLoaded,
+ mediaList: Belt_MapString.update(state.mediaList, action._0, (function (param) {
+ return {
+ TAG: /* Media */1,
+ _0: media
+ };
+ }))
+ };
+ case /* MediaItemFailed */2 :
+ var message = action._1;
+ return {
+ allMediaLoaded: state.allMediaLoaded,
+ mediaList: Belt_MapString.update(state.mediaList, action._0, (function (param) {
+ return {
+ TAG: /* Error */2,
+ _0: message
+ };
+ }))
+ };
+
}
- var media = action._1;
- return {
- allMediaLoaded: state.allMediaLoaded,
- mediaList: Belt_MapString.update(state.mediaList, action._0, (function (param) {
- return {
- TAG: /* Media */1,
- _0: media
- };
- }))
- };
}
var ObserverState = {
@@ -68,9 +82,13 @@ var MediaLoaderObserver = UseObservable.MakeObserver(ObserverState);
var resolveAudio = MediaResolvers.resolveAudio;
+function mediaErrorMessage(prim) {
+ return MediaResolvers.mediaErrorMessage(prim);
+}
+
var resolveSubtitles = MediaResolvers.resolveSubtitles;
-var resolveLottie = MediaResolvers.resolveLottie;
+var resolveJson = MediaResolvers.resolveJson;
var resolveFont = MediaResolvers.resolveFont;
@@ -121,12 +139,12 @@ function processDynamicMedia(imports, wasmController, options) {
})), false)) {
return ;
}
- var match = Utils.$$Array.last(name.split("."));
+ var match = Utils.$$Array.last(name.toLowerCase().split("."));
var tmp;
if (match !== undefined) {
switch (match) {
case "json" :
- tmp = resolveLottie;
+ tmp = resolveJson;
break;
case "jpeg" :
case "jpg" :
@@ -163,10 +181,17 @@ function processDynamicMedia(imports, wasmController, options) {
}
return Belt_Option.map(tmp, (function (resolveFn) {
return Curry._1(resolveFn, {
- name: name,
- url: moduleVal,
- wasmController: wasmController,
- wasmControllerOptions: options
+ name: name,
+ url: moduleVal,
+ wasmController: wasmController,
+ wasmControllerOptions: options
+ }).catch(function (error) {
+ Curry._1(MediaLoaderObserver.dispatch, {
+ TAG: /* MediaItemFailed */2,
+ _0: name,
+ _1: MediaResolvers.mediaErrorMessage(error)
+ });
+ return Promise.resolve(/* MediaResolved */0);
});
}));
})));
@@ -190,8 +215,9 @@ export {
ObserverState ,
MediaLoaderObserver ,
resolveAudio ,
+ mediaErrorMessage ,
resolveSubtitles ,
- resolveLottie ,
+ resolveJson ,
resolveFont ,
resolveImage ,
resolveVideo ,
diff --git a/fframes-editor/src/services/mediaLoader.res b/fframes-editor/src/services/mediaLoader.res
index f2dce340..b3815afd 100644
--- a/fframes-editor/src/services/mediaLoader.res
+++ b/fframes-editor/src/services/mediaLoader.res
@@ -1,6 +1,8 @@
open Belt
module Promise = Js.Promise
+@send external catchMediaError: (Js.Promise.t<'a>, (. 'error) => Js.Promise.t<'a>) => Js.Promise.t<'a> = "catch"
+
type audioInfo = {
duration: float,
sampleRate: int,
@@ -37,6 +39,7 @@ type loadableMedia = Loading(string) | Media(processedMedia) | Error(string)
type action =
| InitMediaProcessing(Js.Dict.t<WasmController.mediaImport>)
| MediaItemProcessed(string, processedMedia)
+ | MediaItemFailed(string, string)
| MediaProcessingFinished
module ObserverState = {
@@ -55,7 +58,7 @@ module ObserverState = {
let reducer = (state, action) => {
switch action {
| InitMediaProcessing(imports) => {
- ...state,
+ allMediaLoaded: false,
mediaList: Map.String.merge(
state.mediaList,
imports
@@ -77,6 +80,10 @@ module ObserverState = {
...state,
mediaList: state.mediaList->Map.String.update(name, _ => Some(Media(media))),
}
+ | MediaItemFailed(name, message) => {
+ ...state,
+ mediaList: state.mediaList->Map.String.update(name, _ => Some(Error(message))),
+ }
| MediaProcessingFinished => {
...state,
allMediaLoaded: true,
@@ -109,9 +116,10 @@ type staticMediaResolver = staticMediaResolverOptions => Js.Promise.t<unit>
type mediaResolveFnWithOptions = mediaResolverOptions => Js.Promise.t<forceTsReturnResolveMedia>
@module("./MediaResolvers") external resolveAudio: mediaResolveFnWithOptions = "resolveAudio"
+@module("./MediaResolvers") external mediaErrorMessage: 'error => string = "mediaErrorMessage"
@module("./MediaResolvers")
external resolveSubtitles: mediaResolveFnWithOptions = "resolveSubtitles"
-@module("./MediaResolvers") external resolveLottie: mediaResolveFnWithOptions = "resolveLottie"
+@module("./MediaResolvers") external resolveJson: mediaResolveFnWithOptions = "resolveJson"
@module("./MediaResolvers") external resolveFont: mediaResolveFnWithOptions = "resolveFont"
@module("./MediaResolvers") external resolveImage: mediaResolveFnWithOptions = "resolveImage"
@module("./MediaResolvers") external resolveVideo: mediaResolveFnWithOptions = "resolveVideo"
@@ -168,10 +176,10 @@ let processDynamicMedia = (
) {
None
} else {
- switch name->Js.String.split(".")->Utils.Array.last {
+ switch name->Js.String.toLowerCase->Js.String.split(".")->Utils.Array.last {
| Some("mp3" | "aac" | "ogg" | "wav" | "pcm" | "flac") => Some(resolveAudio)
| Some("vtt") => Some(resolveSubtitles)
- | Some("json") => Some(resolveLottie)
+ | Some("json") => Some(resolveJson)
| Some("ttf" | "otf") => Some(resolveFont)
| Some("png" | "jpg" | "jpeg") => Some(resolveImage)
| Some("mp4" | "webm" | "mov" | "avi" | "mkv") => Some(resolveVideo)
@@ -182,6 +190,9 @@ let processDynamicMedia = (
url: moduleVal,
wasmController: wasmController,
wasmControllerOptions: options,
+ })->catchMediaError((. error) => {
+ MediaLoaderObserver.dispatch(MediaItemFailed(name, mediaErrorMessage(error)))
+ Promise.resolve(MediaResolved)
})
)
}
diff --git a/fframes-editor/src/ui/Timeline/SceneMapCanvas.bs.js b/fframes-editor/src/ui/Timeline/SceneMapCanvas.bs.js
index 57093d27..530edf4a 100644
--- a/fframes-editor/src/ui/Timeline/SceneMapCanvas.bs.js
+++ b/fframes-editor/src/ui/Timeline/SceneMapCanvas.bs.js
@@ -223,7 +223,7 @@ function renderAudioWaveForm(ctx, endFrame, startFrame, x0, y0, audioSpaceWidth,
switch (media.TAG | 0) {
case /* Media */1 :
var audioInfo$1 = media._0;
- if (audioInfo$1.TAG === /* Audio */3) {
+ if (audioInfo$1.TAG === /* Audio */4) {
audioInfo = audioInfo$1._0;
} else {
exit = 1;
diff --git a/fframes-editor/tests/media-loader.test.mjs b/fframes-editor/tests/media-loader.test.mjs
new file mode 100644
index 00000000..faa10bb6
--- /dev/null
+++ b/fframes-editor/tests/media-loader.test.mjs
@@ -0,0 +1,72 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { build } from "esbuild";
+import { fileURLToPath } from "node:url";
+
+// Exercise the real generated loader and TS resolvers together, with browser I/O mocked.
+const bundle = await build({
+ stdin: {
+ contents: `
+ export { processMedia, MediaLoaderObserver } from "./src/services/mediaLoader.bs.js";
+ export { get as mediaAt } from "rescript/lib/es6/belt_MapString.js";
+ `,
+ resolveDir: fileURLToPath(new URL("../", import.meta.url)),
+ },
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ write: false,
+});
+
+test("failed subtitles settle with asset errors while successful media remains usable", async t => {
+ globalThis.AudioContext = class {};
+ t.after(() => delete globalThis.AudioContext);
+ const { processMedia, MediaLoaderObserver, mediaAt } = await import(
+ `data:text/javascript;base64,${Buffer.from(bundle.outputFiles[0].text).toString("base64")}`
+ );
+ const controller = {
+ populate_static_fonts_db_with_static_fonts() {},
+ get_static_font_data_by_index() {},
+ get_static_audio_data_by_index() {},
+ add_subtitles_source: () => 2,
+ add_json_subtitles_source() {
+ throw new Error("invalid cue timing");
+ },
+ };
+ t.mock.method(globalThis, "fetch", async url => {
+ const status =
+ url === "/missing" ? 404 : url === "/unavailable" ? 503 : 200;
+ return new Response("subtitle data", { status });
+ });
+ const loading = processMedia(
+ {
+ "./missing.vtt": "/missing",
+ "./captions.json": "/unavailable",
+ "./invalid.json": "/invalid",
+ "./good.vtt": "/good",
+ },
+ controller,
+ {}
+ );
+ assert.equal(MediaLoaderObserver.get().allMediaLoaded, false);
+ await loading;
+ const state = MediaLoaderObserver.get();
+ assert.equal(state.allMediaLoaded, true);
+ for (const [file, message] of [
+ ["missing.vtt", /HTTP 404/],
+ ["captions.json", /HTTP 503/],
+ ["invalid.json", /invalid cue timing/],
+ ]) {
+ const asset = mediaAt(state.mediaList, file);
+ assert.equal(asset.TAG, 2, `${file} must be Error, not Loading`);
+ assert.match(asset._0, message);
+ }
+ assert.equal(mediaAt(state.mediaList, "good.vtt").TAG, 1);
+ const retry = processMedia({ "./missing.vtt": "/good" }, controller, {});
+ assert.equal(MediaLoaderObserver.get().allMediaLoaded, false);
+ await retry;
+ assert.equal(
+ mediaAt(MediaLoaderObserver.get().mediaList, "missing.vtt").TAG,
+ 1
+ );
+});
diff --git a/fframes-media/Cargo.toml b/fframes-media/Cargo.toml
index b9705edf..18020ff9 100644
--- a/fframes-media/Cargo.toml
+++ b/fframes-media/Cargo.toml
@@ -18,6 +18,8 @@ ttf-parser = "0.25.1"
itoa = "1.0.14"
kamadak-exif = { workspace = true, optional = true }
base64 = { version = "0.22.1" }
+serde = { version = "1.0", features = ["derive", "rc"] }
+serde_json = "1.0.154"
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen.workspace = true
diff --git a/fframes-media/src/error.rs b/fframes-media/src/error.rs
index eeb78b71..d3217320 100644
--- a/fframes-media/src/error.rs
+++ b/fframes-media/src/error.rs
@@ -5,6 +5,7 @@ pub enum FFramesMediaError {
AudioDecodingError(String),
FontError(ttf_parser::FaceParsingError),
VttError(webvtt_parser::VttError),
+ SubtitlesError(crate::subtitles::SubtitlesError),
NulError(std::ffi::NulError),
MediaDirectoryProvided,
Base64Error(base64::DecodeError),
@@ -33,6 +34,12 @@ impl From<webvtt_parser::VttError> for FFramesMediaError {
}
}
+impl From<crate::subtitles::SubtitlesError> for FFramesMediaError {
+ fn from(err: crate::subtitles::SubtitlesError) -> Self {
+ Self::SubtitlesError(err)
+ }
+}
+
impl From<std::ffi::NulError> for FFramesMediaError {
fn from(err: std::ffi::NulError) -> Self {
Self::NulError(err)
@@ -68,6 +75,7 @@ impl std::fmt::Debug for FFramesMediaError {
Self::ImageError(err) => write!(f, "ImageError: {err:?}"),
Self::FontError(err) => write!(f, "FontError: {err:?}"),
Self::VttError(err) => write!(f, "VttError: {err:?}"),
+ Self::SubtitlesError(err) => write!(f, "SubtitlesError: {err}"),
Self::NulError(err) => write!(f, "{err:?}"),
Self::LibAVAllocationError(what) => write!(f, "libav: Failed to allocate {what}"),
Self::MediaDirectoryProvided => write!(
diff --git a/fframes-media/src/lib.rs b/fframes-media/src/lib.rs
index 67c2e1b1..d2469aec 100644
--- a/fframes-media/src/lib.rs
+++ b/fframes-media/src/lib.rs
@@ -5,6 +5,7 @@ mod font;
mod images;
mod raw_file;
pub mod subtitles;
+mod subtitles_data;
mod video_types;
pub use audio::*;
diff --git a/fframes-media/src/subtitles.rs b/fframes-media/src/subtitles.rs
index eaf81c32..1de0d68f 100644
--- a/fframes-media/src/subtitles.rs
+++ b/fframes-media/src/subtitles.rs
@@ -1,13 +1,30 @@
-use std::{error::Error, fmt::Debug};
+//! Subtitle data and cue lookup for `WebVTT` and ordinary timed-word JSON.
+//!
+//! [`Subtitles::parse`] detects the input format from its content. Both formats
+//! share owned, validated cue data and the same media-loading and frame APIs.
+//! Metadata decodes lazily on first typed access and is cached by application type.
+//! Legacy frame helpers keep inclusive cue ends; [`CaptionTrack::active_cues`]
+//! and the new captions component use half-open `[start, end)` intervals.
+
+use std::fmt::Debug;
pub use webvtt_parser::{self, Vtt, VttCue, VttError};
use webvtt_parser::{OwnedVtt, OwnedVttCue};
-pub type SubtitlesError = FileVttParsingError;
+pub use crate::subtitles_data::{
+ CaptionCue, CaptionError, CaptionMetadata, CaptionTrack, CaptionWord, WordState,
+};
+
+/// Compatibility name for [`CaptionTrack`], the owned VTT/JSON subtitle model.
+pub type Subtitles = CaptionTrack;
+/// Compatibility name for subtitle loading errors.
+pub type SubtitlesError = CaptionError;
pub trait FFramesSubtitlesCue<'a> {
fn text(&'a self) -> &'a str;
}
+/// Legacy subtitle lookup used by frame phrase/cue helpers. Cue ends are inclusive;
+/// cue stacks include only cues starting strictly before `milliseconds + overlap`.
pub trait FFramesSubtitles<'a> {
type Cue: FFramesSubtitlesCue<'a> + Debug;
@@ -108,30 +125,42 @@ impl FFramesSubtitles<'_> for OwnedVtt {
}
}
-// A not for myself in the future:
-// This is a huge pain in the ass for WASM because we have no way to depend on some lifetime coming
-// from outside. So for now simply substitute the types so editor always using OwnedVtt version.
-// Likely need to replace with enum or Cow<'static, Vtt> like alternative.
-//
-#[cfg(not(target_arch = "wasm32"))]
-pub type Subtitles<'a> = Vtt<'a>;
-
-#[cfg(target_arch = "wasm32")]
-pub type Subtitles<'a> = OwnedVtt;
-
-#[derive(Debug)]
-pub enum FileVttParsingError {
- IO(std::io::Error),
- Vtt(VttError),
+impl FFramesSubtitlesCue<'_> for CaptionCue {
+ fn text(&self) -> &str {
+ CaptionCue::phrase(self)
+ }
}
-impl std::fmt::Display for FileVttParsingError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- FileVttParsingError::IO(err) => write!(f, "Failed to read vtt file: {err}"),
- FileVttParsingError::Vtt(error) => write!(f, "Failed to parse vtt file: {error}"),
- }
+impl FFramesSubtitles<'_> for CaptionTrack {
+ type Cue = CaptionCue;
+
+ fn cues_count(&self) -> usize {
+ self.cues().len()
+ }
+
+ fn get_cue_by_time(&self, milliseconds: u64) -> Option<(usize, &Self::Cue)> {
+ let seconds = milliseconds as f64 / 1000.0;
+ self.cues()
+ .iter()
+ .enumerate()
+ .rev()
+ .find(|(_, cue)| cue.start <= seconds && seconds <= cue.end)
}
-}
-impl Error for FileVttParsingError {}
+ fn get_cue_stack(&self, milliseconds: u64, overlap: u64) -> Vec<&Self::Cue> {
+ let joining_seconds = milliseconds.checked_add(overlap).unwrap_or(0) as f64 / 1000.0;
+ self.cues()
+ .iter()
+ .take_while(|cue| cue.start < joining_seconds)
+ .collect()
+ }
+
+ fn get_whole_text(&self) -> Vec<&str> {
+ self.cues().iter().map(CaptionCue::phrase).collect()
+ }
+
+ fn validate_cue_fitting_frame(milliseconds: u64, cue: &Self::Cue) -> bool {
+ let seconds = milliseconds as f64 / 1000.0;
+ cue.start <= seconds && seconds <= cue.end
+ }
+}
diff --git a/fframes-media/src/subtitles_data.rs b/fframes-media/src/subtitles_data.rs
new file mode 100644
index 00000000..34fef04d
--- /dev/null
+++ b/fframes-media/src/subtitles_data.rs
@@ -0,0 +1,881 @@
+//! Owned caption data. All timestamps are seconds on the same clock; ranges are `[start, end)`.
+
+use std::{
+ any::{Any, TypeId},
+ collections::{HashMap, HashSet},
+ error::Error,
+ fmt,
+ ops::{Deref, DerefMut},
+ sync::{Arc, OnceLock},
+};
+
+use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
+use serde_json::{Map, Value};
+
+/// Application-defined JSON data retained by subtitle loaders and callbacks.
+///
+/// The document is parsed once. [`typed`](Self::typed) lazily decodes the retained
+/// object as the requested Serde type, without registration. Each type's successful
+/// value or failure is cached and shared across frames, cloned tracks and threads.
+/// Raw map access (`get`, indexing, `insert`, etc.) remains available.
+#[derive(Clone, Default, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct CaptionMetadata {
+ raw: Arc<Map<String, Value>>,
+ #[serde(skip)]
+ parsed: Arc<OnceLock<TypedMetadata>>,
+}
+
+type MetadataValue = Box<dyn Any + Send + Sync>;
+
+// An append-only type cache keeps references stable without leaking values or
+// returning a reference through a lock guard. Most metadata uses one or two types.
+// OnceLock also serializes concurrent first access, including failed decodes.
+struct TypedMetadata {
+ type_id: TypeId,
+ value: OnceLock<Option<MetadataValue>>,
+ next: OnceLock<Box<TypedMetadata>>,
+}
+
+impl TypedMetadata {
+ fn new<T: 'static>() -> Self {
+ Self {
+ type_id: TypeId::of::<T>(),
+ value: OnceLock::new(),
+ next: OnceLock::new(),
+ }
+ }
+}
+
+impl CaptionMetadata {
+ /// An empty metadata object, also used for captions without metadata.
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Decode `T` on first use, then borrow its cached result. No registration is needed.
+ ///
+ /// Returns `None` for empty or incompatible metadata. Successes and failures
+ /// are cached independently for every requested type. Clones share the cache,
+ /// including before first access. Mutating the raw object detaches that clone's
+ /// cache so its next access decodes the edited data. The JSON string is never
+ /// reparsed, and unrequested application types are never decoded.
+ ///
+ /// ```
+ /// use fframes_media::CaptionTrack;
+ ///
+ /// #[derive(serde::Deserialize)]
+ /// struct Highlight {
+ /// effect: String,
+ /// strength: f32,
+ /// }
+ ///
+ /// let track = CaptionTrack::parse(r#"{"cues":[{"start":0,"end":1,
+ /// "words":[{"text":"Moon","start":0,"end":1,
+ /// "metadata":{"effect":"quartz","strength":0.8}}]}]}"#)?;
+ /// let highlight = track.cues()[0].words[0].metadata.typed::<Highlight>();
+ /// assert_eq!(highlight.unwrap().effect, "quartz");
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
+ /// ```
+ pub fn typed<T: DeserializeOwned + Send + Sync + 'static>(&self) -> Option<&T> {
+ let mut cached = self.parsed.get_or_init(TypedMetadata::new::<T>);
+ while cached.type_id != TypeId::of::<T>() {
+ cached = cached
+ .next
+ .get_or_init(|| Box::new(TypedMetadata::new::<T>()));
+ }
+ cached
+ .value
+ .get_or_init(|| {
+ self.parse::<T>()
+ .map(|value| Box::new(value) as MetadataValue)
+ })
+ .as_deref()?
+ .downcast_ref()
+ }
+
+ /// Decode metadata once for caller-managed preparation, without caching it.
+ ///
+ /// Empty metadata or any deserialization error returns `None`, without
+ /// changing the source data or failing subtitle loading. Serde attributes
+ /// on `T` control defaults and unknown-field handling. Deserialization borrows
+ /// the JSON values, so `T` may contain borrowed strings and no raw map clone
+ /// or intermediate JSON string is needed.
+ ///
+ /// This low-level helper invokes Serde on every call. Prefer
+ /// [`typed`](Self::typed) during rendering. Use
+ /// this helper for explicit preparation that needs borrowed values or a
+ /// caller-managed lifetime.
+ ///
+ /// ```
+ /// use fframes_media::{CaptionMetadata, Subtitles};
+ /// use serde::Deserialize;
+ ///
+ /// #[derive(Deserialize)]
+ /// struct Highlight<'a> {
+ /// effect: &'a str,
+ /// strength: f32,
+ /// }
+ ///
+ /// let track = Subtitles::parse(r#"{"cues":[{"start":0,"end":1,"text":"Moon",
+ /// "metadata":{"effect":"quartz","strength":0.8}}]}"#)?;
+ /// let settings = track.cues()[0].metadata.parse::<Highlight<'_>>();
+ /// assert_eq!(settings.unwrap().effect, "quartz");
+ /// assert!(CaptionMetadata::new().parse::<Highlight<'_>>().is_none());
+ /// # Ok::<(), Box<dyn std::error::Error>>(())
+ /// ```
+ pub fn parse<'de, T>(&'de self) -> Option<T>
+ where
+ T: Deserialize<'de>,
+ {
+ if self.raw.is_empty() {
+ return None;
+ }
+ T::deserialize(MetadataDeserializer(&self.raw)).ok()
+ }
+
+ /// Recover the raw JSON object, cloning only when another consumer shares it.
+ pub fn into_inner(self) -> Map<String, Value> {
+ Arc::unwrap_or_clone(self.raw)
+ }
+}
+
+impl fmt::Debug for CaptionMetadata {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_tuple("CaptionMetadata").field(&self.raw).finish()
+ }
+}
+
+impl PartialEq for CaptionMetadata {
+ fn eq(&self, other: &Self) -> bool {
+ self.raw == other.raw
+ }
+}
+
+impl From<Map<String, Value>> for CaptionMetadata {
+ fn from(metadata: Map<String, Value>) -> Self {
+ Self {
+ raw: Arc::new(metadata),
+ parsed: Arc::default(),
+ }
+ }
+}
+
+impl Deref for CaptionMetadata {
+ type Target = Map<String, Value>;
+
+ fn deref(&self) -> &Self::Target {
+ &self.raw
+ }
+}
+
+impl DerefMut for CaptionMetadata {
+ fn deref_mut(&mut self) -> &mut Self::Target {
+ self.parsed = Arc::default();
+ Arc::make_mut(&mut self.raw)
+ }
+}
+
+// serde_json's borrowed Map deserializer handles objects and enums, but forwards
+// Option and newtype structs to visit_map. Supply the same wrapper semantics as
+// deserializing a Value::Object, without cloning the map into a temporary Value.
+struct MetadataDeserializer<'de>(&'de Map<String, Value>);
+
+impl<'de> Deserializer<'de> for MetadataDeserializer<'de> {
+ type Error = serde_json::Error;
+
+ fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ self.0.deserialize_any(visitor)
+ }
+
+ fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_some(self)
+ }
+
+ fn deserialize_newtype_struct<V>(
+ self,
+ _name: &'static str,
+ visitor: V,
+ ) -> Result<V::Value, Self::Error>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_newtype_struct(self)
+ }
+
+ fn deserialize_enum<V>(
+ self,
+ name: &'static str,
+ variants: &'static [&'static str],
+ visitor: V,
+ ) -> Result<V::Value, Self::Error>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ self.0.deserialize_enum(name, variants, visitor)
+ }
+
+ fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error>
+ where
+ V: serde::de::Visitor<'de>,
+ {
+ visitor.visit_unit()
+ }
+
+ serde::forward_to_deserialize_any! {
+ bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
+ bytes byte_buf unit unit_struct seq tuple tuple_struct map struct identifier
+ }
+}
+
+/// A caption input or preparation error, including the offending input field where possible.
+#[derive(Debug)]
+pub enum CaptionError {
+ /// Data or rendering options that cannot produce a valid caption.
+ Invalid { path: String, message: String },
+ /// Malformed JSON, an unknown field, or a value with the wrong type.
+ Json(serde_json::Error),
+ /// A `WebVTT` parsing error.
+ Vtt(String),
+}
+
+impl CaptionError {
+ /// Construct an error for a particular input field, such as `cues[0].words[1].end`.
+ pub fn invalid(path: impl Into<String>, message: impl Into<String>) -> Self {
+ Self::Invalid {
+ path: path.into(),
+ message: message.into(),
+ }
+ }
+}
+
+impl fmt::Display for CaptionError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Invalid { path, message } => write!(f, "{path}: {message}"),
+ Self::Json(error) => write!(f, "caption JSON: {error}"),
+ Self::Vtt(error) => write!(f, "caption WebVTT: {error}"),
+ }
+ }
+}
+
+impl Error for CaptionError {
+ fn source(&self) -> Option<&(dyn Error + 'static)> {
+ match self {
+ Self::Json(error) => Some(error),
+ _ => None,
+ }
+ }
+}
+
+impl From<serde_json::Error> for CaptionError {
+ fn from(value: serde_json::Error) -> Self {
+ Self::Json(value)
+ }
+}
+
+/// A word's timing state. An active word occupies `[start, end)`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WordState {
+ Upcoming,
+ Active,
+ Spoken,
+}
+
+fn space_before_default() -> bool {
+ true
+}
+
+fn is_true(value: &bool) -> bool {
+ *value
+}
+
+/// One timed display token. Usually a word, but it may be punctuation or a CJK segment.
+///
+/// `space_before` defaults to true. Set it to false for punctuation or adjacent tokens;
+/// the renderer always ignores it for the first token of a line.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct CaptionWord {
+ pub text: String,
+ pub start: f64,
+ pub end: f64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub id: Option<String>,
+ #[serde(default = "space_before_default", skip_serializing_if = "is_true")]
+ pub space_before: bool,
+ /// Application-defined data, such as authored layout, motion or highlight settings.
+ /// The subtitle parser preserves this object without interpreting its keys.
+ #[serde(default, skip_serializing_if = "Map::is_empty")]
+ pub metadata: CaptionMetadata,
+}
+
+impl CaptionWord {
+ /// Declare a word with timestamps in seconds. The track validates its timing.
+ pub fn new(text: impl Into<String>, start: f64, end: f64) -> Self {
+ Self {
+ text: text.into(),
+ start,
+ end,
+ id: None,
+ space_before: true,
+ metadata: CaptionMetadata::new(),
+ }
+ }
+
+ /// Give the word a stable identifier within its cue.
+ pub fn id(mut self, id: impl Into<String>) -> Self {
+ self.id = Some(id.into());
+ self
+ }
+
+ /// Control whether a separator is inserted before this token.
+ pub fn space_before(mut self, space_before: bool) -> Self {
+ self.space_before = space_before;
+ self
+ }
+
+ /// Attach renderer-specific data without changing this word's text or timing.
+ pub fn with_metadata(mut self, metadata: impl Into<CaptionMetadata>) -> Self {
+ self.metadata = metadata.into();
+ self
+ }
+
+ /// The timing state at a time in seconds. NaN has no active word.
+ pub fn state_at(&self, seconds: f64) -> WordState {
+ if seconds.is_nan() || seconds < self.start {
+ WordState::Upcoming
+ } else if seconds >= self.end {
+ WordState::Spoken
+ } else {
+ WordState::Active
+ }
+ }
+
+ /// Elapsed fraction of this word, clamped to `0..=1`; NaN returns zero.
+ pub fn progress_at(&self, seconds: f64) -> f32 {
+ if seconds.is_nan() {
+ 0.0
+ } else {
+ ((seconds - self.start) / (self.end - self.start)).clamp(0.0, 1.0) as f32
+ }
+ }
+}
+
+/// A display interval containing either plain `text` or explicitly timed `words`.
+///
+/// The interval may start before its first word or end after its last word, so a whole
+/// phrase can remain on screen during pauses. Word timestamps use the track clock rather
+/// than time relative to this cue. Overlapping cues can represent different speakers.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct CaptionCue {
+ pub start: f64,
+ pub end: f64,
+ #[serde(default, skip_serializing_if = "String::is_empty")]
+ pub text: String,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub words: Vec<CaptionWord>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub id: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub speaker: Option<String>,
+ /// Application-defined cue data. Interpretation and validation belong to the renderer.
+ #[serde(default, skip_serializing_if = "Map::is_empty")]
+ pub metadata: CaptionMetadata,
+ /// The original `WebVTT` identifier. It is not required to be unique.
+ #[serde(skip)]
+ pub name: Option<String>,
+ /// Raw `WebVTT` cue note, when present.
+ #[serde(skip)]
+ pub note: Option<String>,
+ /// Parsed positioning settings, retained for a renderer to interpret.
+ #[serde(skip)]
+ pub cue_settings: Option<webvtt_parser::VttCueSettings>,
+ #[serde(skip)]
+ resolved_text: String,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct CueInput {
+ start: f64,
+ end: f64,
+ #[serde(default)]
+ text: String,
+ #[serde(default)]
+ words: Vec<CaptionWord>,
+ #[serde(default)]
+ id: Option<String>,
+ #[serde(default)]
+ speaker: Option<String>,
+ #[serde(default)]
+ metadata: CaptionMetadata,
+}
+
+impl<'de> Deserialize<'de> for CaptionCue {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let input = CueInput::deserialize(deserializer)?;
+ let mut cue = Self {
+ start: input.start,
+ end: input.end,
+ text: input.text,
+ words: input.words,
+ id: input.id,
+ speaker: input.speaker,
+ metadata: input.metadata,
+ name: None,
+ note: None,
+ cue_settings: None,
+ resolved_text: String::new(),
+ };
+ cue.resolved_text = cue.display_text();
+ Ok(cue)
+ }
+}
+
+impl CaptionCue {
+ /// A phrase with explicitly timed words, displayed over `[start, end)` seconds.
+ pub fn words(start: f64, end: f64, words: impl IntoIterator<Item = CaptionWord>) -> Self {
+ let mut cue = Self {
+ start,
+ end,
+ text: String::new(),
+ words: words.into_iter().collect(),
+ id: None,
+ speaker: None,
+ metadata: CaptionMetadata::new(),
+ name: None,
+ note: None,
+ cue_settings: None,
+ resolved_text: String::new(),
+ };
+ cue.resolved_text = cue.display_text();
+ cue
+ }
+
+ /// A phrase without word timings. No per-word timestamps are invented.
+ pub fn text(start: f64, end: f64, text: impl Into<String>) -> Self {
+ let text = text.into();
+ Self {
+ start,
+ end,
+ resolved_text: text.clone(),
+ text,
+ words: Vec::new(),
+ id: None,
+ speaker: None,
+ metadata: CaptionMetadata::new(),
+ name: None,
+ note: None,
+ cue_settings: None,
+ }
+ }
+
+ /// Give the cue a stable identifier within its track.
+ pub fn id(mut self, id: impl Into<String>) -> Self {
+ self.id = Some(id.into());
+ self
+ }
+
+ /// Label the speaker without inferring a rendering style or voice identity.
+ pub fn speaker(mut self, speaker: impl Into<String>) -> Self {
+ self.speaker = Some(speaker.into());
+ self
+ }
+
+ /// Attach renderer-specific data without changing this cue's text or timing.
+ pub fn with_metadata(mut self, metadata: impl Into<CaptionMetadata>) -> Self {
+ self.metadata = metadata.into();
+ self
+ }
+
+ /// Reconstruct the phrase without losing the declared token separators.
+ pub fn display_text(&self) -> String {
+ if self.words.is_empty() {
+ return self.text.clone();
+ }
+ let mut result = String::new();
+ for (index, word) in self.words.iter().enumerate() {
+ if index > 0 && word.space_before {
+ result.push(' ');
+ }
+ result.push_str(&word.text);
+ }
+ result
+ }
+
+ /// The complete phrase, cached when the containing subtitle track is validated.
+ /// Timed-word cues preserve their explicit token separators.
+ pub fn phrase(&self) -> &str {
+ if self.words.is_empty() {
+ &self.text
+ } else {
+ &self.resolved_text
+ }
+ }
+}
+
+/// A validated, owned caption track suitable for Rust declarations or runtime JSON.
+///
+/// Cues are ordered by start time and may overlap. Words within a cue are ordered and do
+/// not overlap. IDs are optional; cue IDs are unique within the track and word IDs within
+/// each cue. All times are finite, nonnegative seconds with end-exclusive intervals.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+pub struct CaptionTrack {
+ cues: Arc<[CaptionCue]>,
+ #[serde(skip)]
+ identity: Arc<()>,
+ /// Top-level `WebVTT` metadata, preserved during parsing.
+ #[serde(skip)]
+ pub slugs: HashMap<String, String>,
+ /// Raw global `WebVTT` styling, when exposed by the parser.
+ #[serde(skip)]
+ pub style: Option<String>,
+ #[serde(skip)]
+ source_vtt: bool,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct TrackInput {
+ cues: Vec<CaptionCue>,
+}
+
+// Dispatch top-level JSON without an intermediate Value tree. Feeding `cues`
+// directly into the ordinary cue/word deserializers preserves duplicate-field
+// errors that would otherwise be lost when collecting JSON keys into a map.
+struct SubtitleDocumentInput {
+ cues: Option<Vec<CaptionCue>>,
+}
+
+impl<'de> Deserialize<'de> for SubtitleDocumentInput {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ struct DocumentVisitor;
+
+ impl<'de> serde::de::Visitor<'de> for DocumentVisitor {
+ type Value = SubtitleDocumentInput;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("a JSON object with optional subtitle cues")
+ }
+
+ fn visit_map<A: serde::de::MapAccess<'de>>(
+ self,
+ mut map: A,
+ ) -> Result<Self::Value, A::Error> {
+ let mut cues = None;
+ let mut unknown_field = None;
+ while let Some(key) = map.next_key::<String>()? {
+ if key == "cues" {
+ if cues.is_some() {
+ return Err(serde::de::Error::duplicate_field("cues"));
+ }
+ cues = Some(map.next_value::<Vec<CaptionCue>>()?);
+ } else {
+ map.next_value::<serde::de::IgnoredAny>()?;
+ unknown_field.get_or_insert(key);
+ }
+ }
+ if cues.is_some()
+ && let Some(field) = unknown_field
+ {
+ return Err(serde::de::Error::unknown_field(&field, &["cues"]));
+ }
+ Ok(SubtitleDocumentInput { cues })
+ }
+ }
+
+ deserializer.deserialize_map(DocumentVisitor)
+ }
+}
+
+impl<'de> Deserialize<'de> for CaptionTrack {
+ fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let input = TrackInput::deserialize(deserializer)?;
+ Self::new(input.cues).map_err(serde::de::Error::custom)
+ }
+}
+
+impl CaptionTrack {
+ /// Validate and own a sequence of cues. An empty track is valid.
+ pub fn new(cues: impl IntoIterator<Item = CaptionCue>) -> Result<Self, CaptionError> {
+ Self::from_cues(cues, false)
+ }
+
+ fn from_cues(
+ cues: impl IntoIterator<Item = CaptionCue>,
+ source_vtt: bool,
+ ) -> Result<Self, CaptionError> {
+ let mut track = Self {
+ cues: cues.into_iter().collect::<Vec<_>>().into(),
+ identity: Arc::new(()),
+ slugs: HashMap::new(),
+ style: None,
+ source_vtt,
+ };
+ track.validate()?;
+ for cue in Arc::make_mut(&mut track.cues) {
+ cue.resolved_text = cue.display_text();
+ }
+ Ok(track)
+ }
+
+ /// Parse ordinary JSON or `WebVTT`. The format is detected from its contents,
+ /// independent of the filename. All parsed data is owned.
+ pub fn parse(content: &str) -> Result<Self, CaptionError> {
+ let content = normalize_input(content);
+ if content.starts_with("WEBVTT") {
+ Self::from_vtt(content)
+ } else if content.starts_with('{') {
+ Self::from_json(content)
+ } else {
+ Err(CaptionError::invalid(
+ "format",
+ "expected a WEBVTT document or a JSON object with a cues array",
+ ))
+ }
+ }
+
+ /// Classify and load a JSON document with a single textual JSON parse.
+ ///
+ /// Returns a validated subtitle track when the top-level object declares
+ /// `cues`, or `None` for other valid JSON documents. Malformed JSON and invalid
+ /// subtitle data return an error. Media loaders can retain this result instead
+ /// of parsing the document once for format detection and again for loading.
+ pub fn parse_json_document(content: &str) -> Result<Option<Self>, CaptionError> {
+ let content = normalize_input(content);
+ if !content.starts_with('{') {
+ // Non-object JSON is not subtitles, but must still be valid JSON.
+ serde_json::from_str::<serde::de::IgnoredAny>(content)?;
+ return Ok(None);
+ }
+ let input: SubtitleDocumentInput = serde_json::from_str(content)?;
+ input.cues.map(Self::new).transpose()
+ }
+
+ /// Whether a valid JSON object declares subtitle cues. Cue validation is left
+ /// to `parse`, so malformed cue values still produce subtitle-specific errors.
+ /// This is an inspection helper. Loaders should use [`Self::parse_json_document`]
+ /// and retain its result to avoid parsing the document again.
+ pub fn is_json(content: &str) -> bool {
+ serde_json::from_str::<serde_json::Value>(normalize_input(content)).is_ok_and(|value| {
+ value
+ .as_object()
+ .is_some_and(|object| object.contains_key("cues"))
+ })
+ }
+
+ /// Equivalent to [`Self::is_json`]. Loaders should prefer [`Self::parse_json_document`].
+ pub fn is_json_subtitles(content: &str) -> bool {
+ Self::is_json(content)
+ }
+
+ /// Parse the canonical JSON representation and validate all cue and word timings.
+ pub fn from_json(json: &str) -> Result<Self, CaptionError> {
+ let input: TrackInput = serde_json::from_str(normalize_input(json))?;
+ Self::new(input.cues)
+ }
+
+ /// Serialize the canonical JSON representation with indented formatting.
+ /// Imported zero-duration VTT cues need a duration (or removal) before JSON export.
+ pub fn to_json_pretty(&self) -> Result<String, CaptionError> {
+ self.validate_cues(false)?;
+ Ok(serde_json::to_string_pretty(self)?)
+ }
+
+ /// Import `WebVTT` through the existing parser, preserving raw payload and metadata.
+ /// Word timestamps are never inferred from phrase text or inline markup.
+ /// Instantaneous VTT cues remain available to inclusive legacy lookups;
+ /// they are never active in the new half-open caption API.
+ pub fn from_vtt(vtt: &str) -> Result<Self, CaptionError> {
+ let parsed = webvtt_parser::Vtt::parse(normalize_input(vtt))
+ .map_err(|error| CaptionError::Vtt(error.to_string()))?;
+ let slugs = parsed
+ .slugs
+ .into_iter()
+ .map(|(key, value)| (key.to_owned(), value.to_owned()))
+ .collect();
+ let style = parsed.style.map(str::to_owned);
+ let mut cues = Vec::with_capacity(parsed.cues.len());
+ for cue in parsed.cues {
+ // WebVTT permits spacer cues; they have no visible content.
+ if cue.text.trim().is_empty() {
+ continue;
+ }
+ let mut imported = CaptionCue::text(
+ cue.start.as_milliseconds() as f64 / 1000.0,
+ cue.end.as_milliseconds() as f64 / 1000.0,
+ cue.text,
+ );
+ imported.name = cue.name.map(str::to_owned);
+ imported.note = cue.note.map(str::to_owned);
+ imported.cue_settings = cue.cue_settings;
+ cues.push(imported);
+ }
+ let mut track = Self::from_cues(cues, true)?;
+ track.slugs = slugs;
+ track.style = style;
+ Ok(track)
+ }
+
+ /// Whether this track was parsed from `WebVTT`. Raw payload markup/settings
+ /// remain available for a renderer to interpret explicitly.
+ pub fn is_vtt(&self) -> bool {
+ self.source_vtt
+ }
+
+ /// The ordered, validated cues. Modify through a new track so validation stays intact.
+ pub fn cues(&self) -> &[CaptionCue] {
+ &self.cues
+ }
+
+ /// Clones share this token, while a newly loaded revision receives a new identity.
+ #[doc(hidden)]
+ pub fn cache_identity(&self) -> &Arc<()> {
+ &self.identity
+ }
+
+ /// All visible cues at `seconds`, including simultaneously active speakers.
+ pub fn active_cues(&self, seconds: f64) -> impl Iterator<Item = (usize, &CaptionCue)> {
+ self.cues
+ .iter()
+ .enumerate()
+ .take_while(move |(_, cue)| cue.start <= seconds)
+ .filter(move |(_, cue)| seconds < cue.end)
+ }
+
+ /// Validate timing, content, ordering and optional identifiers.
+ pub fn validate(&self) -> Result<(), CaptionError> {
+ self.validate_cues(self.source_vtt)
+ }
+
+ fn validate_cues(&self, allow_instant_vtt: bool) -> Result<(), CaptionError> {
+ let mut cue_ids = HashSet::new();
+ let mut previous_start = 0.0;
+ for (cue_index, cue) in self.cues.iter().enumerate() {
+ let path = format!("cues[{cue_index}]");
+ validate_interval(cue.start, cue.end, &path, allow_instant_vtt)?;
+ if cue.start < previous_start {
+ return Err(CaptionError::invalid(
+ format!("{path}.start"),
+ "cues must be ordered by start time",
+ ));
+ }
+ previous_start = cue.start;
+ validate_id(cue.id.as_deref(), &mut cue_ids, &format!("{path}.id"))?;
+ if cue
+ .speaker
+ .as_ref()
+ .is_some_and(|value| value.trim().is_empty())
+ {
+ return Err(CaptionError::invalid(
+ format!("{path}.speaker"),
+ "speaker must not be blank",
+ ));
+ }
+ if cue.words.is_empty() {
+ if cue.text.trim().is_empty() {
+ return Err(CaptionError::invalid(
+ &path,
+ "provide nonempty text or a nonempty words array",
+ ));
+ }
+ continue;
+ }
+ if !cue.text.is_empty() {
+ return Err(CaptionError::invalid(
+ &path,
+ "provide either text or words, not both",
+ ));
+ }
+ let mut word_ids = HashSet::new();
+ let mut previous_end = cue.start;
+ for (word_index, word) in cue.words.iter().enumerate() {
+ let word_path = format!("{path}.words[{word_index}]");
+ validate_interval(word.start, word.end, &word_path, false)?;
+ if word.start < cue.start || word.end > cue.end {
+ return Err(CaptionError::invalid(
+ &word_path,
+ "word interval must be contained in its cue interval",
+ ));
+ }
+ if word.start < previous_end {
+ return Err(CaptionError::invalid(
+ format!("{word_path}.start"),
+ "words must be ordered and must not overlap",
+ ));
+ }
+ if word.text.trim().is_empty() {
+ return Err(CaptionError::invalid(
+ format!("{word_path}.text"),
+ "word text must not be blank",
+ ));
+ }
+ validate_id(
+ word.id.as_deref(),
+ &mut word_ids,
+ &format!("{word_path}.id"),
+ )?;
+ previous_end = word.end;
+ }
+ }
+ Ok(())
+ }
+}
+
+fn normalize_input(content: &str) -> &str {
+ content
+ .trim_start()
+ .strip_prefix('\u{feff}')
+ .unwrap_or(content.trim_start())
+ .trim_start()
+}
+
+fn validate_interval(
+ start: f64,
+ end: f64,
+ path: &str,
+ allow_instant: bool,
+) -> Result<(), CaptionError> {
+ for (name, value) in [("start", start), ("end", end)] {
+ if !value.is_finite() || value < 0.0 {
+ return Err(CaptionError::invalid(
+ format!("{path}.{name}"),
+ "time must be a finite, nonnegative number of seconds",
+ ));
+ }
+ }
+ if end < start || (!allow_instant && end == start) {
+ return Err(CaptionError::invalid(
+ format!("{path}.end"),
+ "end must be greater than start (intervals are end-exclusive)",
+ ));
+ }
+ Ok(())
+}
+
+fn validate_id<'a>(
+ id: Option<&'a str>,
+ seen: &mut HashSet<&'a str>,
+ path: &str,
+) -> Result<(), CaptionError> {
+ if let Some(id) = id {
+ if id.trim().is_empty() {
+ return Err(CaptionError::invalid(path, "id must not be blank"));
+ }
+ if !seen.insert(id) {
+ return Err(CaptionError::invalid(
+ path,
+ "id must be unique in its scope",
+ ));
+ }
+ }
+ Ok(())
+}
diff --git a/fframes-media/tests/subtitles.rs b/fframes-media/tests/subtitles.rs
new file mode 100644
index 00000000..a076114e
--- /dev/null
+++ b/fframes-media/tests/subtitles.rs
@@ -0,0 +1,268 @@
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use fframes_media::{CaptionCue, CaptionTrack, CaptionWord, Subtitles, WordState};
+use serde::{Deserialize, Deserializer};
+
+#[derive(Debug, Deserialize, PartialEq)]
+#[serde(tag = "effect", rename_all = "kebab-case", deny_unknown_fields)]
+enum Highlight {
+ Outline { color: String },
+ Glow { strength: f32 },
+}
+
+#[test]
+fn legacy_cue_boundaries_match_borrowed_and_owned_vtt() {
+ use fframes_media::{FFramesSubtitles, Vtt};
+
+ fn check<'a, T: FFramesSubtitles<'a>>(track: &T) {
+ let cue = track.get_cue_by_time(3000).unwrap().1;
+ assert!(T::validate_cue_fitting_frame(3000, cue));
+ assert!(track.get_cue_by_time(3001).is_none());
+ assert_eq!(track.get_cue_stack(1200, 0).len(), 0);
+ assert_eq!(track.get_cue_stack(1199, 1).len(), 0);
+ assert_eq!(track.get_cue_stack(1201, 0).len(), 1);
+ assert!(track.get_cue_stack(u64::MAX, 1).is_empty());
+ }
+
+ let input = "WEBVTT\n\n00:01.200 --> 00:03.000\nKeep the last frame\n";
+ let borrowed = Vtt::parse(input).unwrap();
+ check(&borrowed);
+ check(&borrowed.to_owned());
+ let track = CaptionTrack::parse(input).unwrap();
+ check(&track);
+ assert_eq!(track.active_cues(3.0).count(), 0);
+
+ // A legacy zero-duration cue still draws at its one inclusive instant.
+ let instant = "WEBVTT\n\n00:01.000 --> 00:01.000\nInstant\n";
+ let borrowed = Vtt::parse(instant).unwrap();
+ let track = CaptionTrack::parse(instant).unwrap();
+ assert_eq!(borrowed.get_cue_by_time(1000).unwrap().1.text, "Instant");
+ assert_eq!(track.get_cue_by_time(1000).unwrap().1.phrase(), "Instant");
+ assert_eq!(track.active_cues(1.0).count(), 0);
+ assert!(
+ track.to_json_pretty().is_err(),
+ "JSON still requires positive durations"
+ );
+}
+
+#[test]
+fn vtt_and_json_share_owned_data_and_preserve_legacy_lookup() {
+ use fframes_media::FFramesSubtitles;
+ let vtt =
+ String::from("\u{feff}WEBVTT\r\n\r\nintro\r\n00:00.500 --> 00:02.000\r\nHello world\r\n");
+ let track = Subtitles::parse(&vtt).unwrap();
+ drop(vtt);
+ assert!(track.is_vtt());
+ assert_eq!(track.cues()[0].name.as_deref(), Some("intro"));
+ assert_eq!(track.cues()[0].words, []);
+ assert!(track.get_cue_by_time(499).is_none());
+ assert_eq!(
+ track.get_cue_by_time(500).unwrap().1.phrase(),
+ "Hello world"
+ );
+ assert!(track.get_cue_by_time(2000).is_some());
+ assert!(track.get_cue_by_time(2001).is_none());
+ assert_eq!(track.active_cues(2.0).count(), 0);
+
+ let json = track.to_json_pretty().unwrap();
+ let reloaded = Subtitles::parse(&json).unwrap();
+ assert_eq!(reloaded.get_whole_text(), ["Hello world"]);
+ assert_eq!(reloaded.cues()[0].start, 0.5);
+ assert!(!reloaded.is_vtt());
+
+ let long =
+ Subtitles::parse("WEBVTT\n\n01:02:03.456 --> 01:02:05.000\nFirst line\nSecond line\n")
+ .unwrap();
+ assert_eq!(long.cues()[0].start, 3723.456);
+ assert_eq!(long.cues()[0].phrase(), "First line\nSecond line");
+ assert_eq!(Subtitles::parse("WEBVTT\n\n").unwrap().cues(), []);
+ let spacers = Subtitles::parse(concat!(
+ "WEBVTT\n\n00:00.000 --> 00:01.000\n\n",
+ "00:01.000 --> 00:02.000\n \t\n\n",
+ "00:02.000 --> 00:03.000\nVisible\n"
+ ))
+ .unwrap();
+ assert_eq!(spacers.get_whole_text(), ["Visible"]);
+ assert_eq!(spacers.cues()[0].start, 2.0);
+ for invalid in [
+ "WEBVTT\n\n00:60.000 --> 01:01.000\nbad minutes\n",
+ "WEBVTT\n\n00:00.000 --> 00:01.000\nok\n\ntruncated cue",
+ ] {
+ assert!(Subtitles::parse(invalid).is_err());
+ }
+}
+
+#[test]
+fn timed_tokens_preserve_gaps_punctuation_and_overlapping_speakers() {
+ let track = CaptionTrack::new([
+ CaptionCue::words(
+ 0.0,
+ 3.0,
+ [
+ CaptionWord::new("Hello", 0.0, 0.5),
+ CaptionWord::new(",", 0.5, 0.6).space_before(false),
+ CaptionWord::new("world", 1.0, 2.0),
+ ],
+ )
+ .speaker("A"),
+ CaptionCue::text(1.0, 2.5, "Yes").speaker("B"),
+ ])
+ .unwrap();
+ assert_eq!(track.cues()[0].phrase(), "Hello, world");
+ assert_eq!(track.active_cues(1.5).count(), 2);
+ assert_eq!(track.active_cues(3.0).count(), 0);
+ let words = &track.cues()[0].words;
+ assert_eq!(words[0].state_at(0.5), WordState::Spoken);
+ assert_eq!(words[2].state_at(0.8), WordState::Upcoming);
+ assert_eq!(words[2].progress_at(1.5), 0.5);
+ assert_eq!(words[2].state_at(f64::NAN), WordState::Upcoming);
+}
+
+#[test]
+fn invalid_documents_fail_before_rendering() {
+ for (json, field) in [
+ (r#"{"cues":[{"start":0,"end":0,"text":"x"}]}"#, "end"),
+ (r#"{"cues":[{"start":-1,"end":1,"text":"x"}]}"#, "start"),
+ (r#"{"cues":[{"start":0,"end":1,"text":" "}]}"#, "nonempty"),
+ (
+ r#"{"cues":[{"start":0,"end":1,"words":[{"text":"x","start":0,"end":2}]}]}"#,
+ "words[0]",
+ ),
+ (
+ r#"{"cues":[{"start":0,"end":2,"words":[{"text":"a","start":0,"end":1},{"text":"b","start":0.5,"end":2}]}]}"#,
+ "words[1].start",
+ ),
+ (
+ r#"{"cues":[{"start":0,"end":1,"text":"x","typo":1}]}"#,
+ "typo",
+ ),
+ (
+ r#"{"cues":[{"start":0,"end":1,"text":"x","text":"y"}]}"#,
+ "duplicate field",
+ ),
+ (r#"{"cues":[],"cues":[]}"#, "duplicate field"),
+ ] {
+ assert!(
+ Subtitles::parse(json)
+ .unwrap_err()
+ .to_string()
+ .contains(field),
+ "{json}"
+ );
+ assert!(
+ Subtitles::parse_json_document(json).is_err(),
+ "dispatch accepted {json}"
+ );
+ }
+ assert!(
+ Subtitles::parse_json_document(r#"{"v":"5.7","layers":[]}"#)
+ .unwrap()
+ .is_none()
+ );
+ assert!(Subtitles::parse_json_document("[1,2,3]").unwrap().is_none());
+ assert!(CaptionTrack::new([CaptionCue::text(f64::NAN, 1.0, "bad")]).is_err());
+}
+
+#[test]
+fn metadata_decodes_once_across_frames_clones_and_threads_including_failures() {
+ static DECODES: AtomicUsize = AtomicUsize::new(0);
+ struct Counted(Highlight);
+ impl<'de> Deserialize<'de> for Counted {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ DECODES.fetch_add(1, Ordering::SeqCst);
+ Highlight::deserialize(d).map(Self)
+ }
+ }
+ #[derive(Deserialize)]
+ struct Label {
+ effect: String,
+ }
+ let input = r##"{"cues":[{"start":0,"end":2,"words":[
+ {"text":"valid","start":0,"end":1,"metadata":{"effect":"outline","color":"#ffffff"}},
+ {"text":"invalid","start":1,"end":2,"metadata":{"effect":"unknown"}}
+ ]}]}"##;
+ let track = CaptionTrack::parse(input).unwrap();
+ assert_eq!(DECODES.load(Ordering::SeqCst), 0);
+ // A second schema can be requested independently, without registration.
+ assert_eq!(
+ track.cues()[0].words[0]
+ .metadata
+ .typed::<Label>()
+ .unwrap()
+ .effect,
+ "outline"
+ );
+ assert_eq!(DECODES.load(Ordering::SeqCst), 0);
+ let clone = track.clone();
+ assert!(
+ std::ptr::eq(track.cues(), clone.cues()),
+ "cloning must share cue storage"
+ );
+ std::thread::scope(|scope| {
+ for _ in 0..8 {
+ let cloned = track.clone();
+ scope.spawn(move || {
+ for _frame in 0..120 {
+ let words = &cloned.cues()[0].words;
+ assert!(matches!(
+ words[0].metadata.typed::<Counted>().unwrap().0,
+ Highlight::Outline { .. }
+ ));
+ assert!(words[1].metadata.typed::<Counted>().is_none());
+ assert_eq!(
+ words[1].metadata.typed::<Label>().unwrap().effect,
+ "unknown"
+ );
+ assert!(words[0].metadata.typed::<Highlight>().is_some());
+ }
+ });
+ }
+ });
+ assert_eq!(
+ DECODES.load(Ordering::SeqCst),
+ 2,
+ "one successful and one failed decode"
+ );
+ assert!(std::ptr::eq(
+ track.cues()[0].words[0]
+ .metadata
+ .typed::<Counted>()
+ .unwrap(),
+ clone.cues()[0].words[0]
+ .metadata
+ .typed::<Counted>()
+ .unwrap(),
+ ));
+ assert!(std::ptr::eq(track.cues(), clone.cues()));
+ assert_eq!(DECODES.load(Ordering::SeqCst), 2);
+}
+
+#[test]
+fn metadata_edits_detach_the_cache_without_changing_other_consumers() {
+ let original = CaptionTrack::parse(
+ r#"{"cues":[{"start":0,"end":1,"words":[{"text":"x","start":0,"end":1,"metadata":{"effect":"glow","strength":0.5}}]}]}"#,
+ ).unwrap();
+ let old = &original.cues()[0].words[0].metadata;
+ assert_eq!(
+ old.typed::<Highlight>(),
+ Some(&Highlight::Glow { strength: 0.5 })
+ );
+ let mut cues = original.cues().to_vec();
+ cues[0].words[0]
+ .metadata
+ .insert("strength".into(), serde_json::json!(0.8));
+ assert_eq!(
+ cues[0].words[0].metadata.typed::<Highlight>(),
+ Some(&Highlight::Glow { strength: 0.8 })
+ );
+ let edited = CaptionTrack::new(cues).unwrap();
+ assert_eq!(
+ edited.cues()[0].words[0].metadata.typed::<Highlight>(),
+ Some(&Highlight::Glow { strength: 0.8 })
+ );
+ assert_eq!(
+ old.typed::<Highlight>(),
+ Some(&Highlight::Glow { strength: 0.5 })
+ );
+ assert!(!std::ptr::eq(original.cues(), edited.cues()));
+}
diff --git a/fframes/Cargo.toml b/fframes/Cargo.toml
index 1924687d..4df37964 100644
--- a/fframes/Cargo.toml
+++ b/fframes/Cargo.toml
@@ -69,6 +69,8 @@ default = ["cpu_renderer"]
cpu_renderer = ["svgr"]
# `fframes::cli`: a ready made command line (render, frames, contact sheets, inspect, audio)
cli = ["cpu_renderer", "dep:clap", "dep:serde_json"]
+# Declarative SVG caption rendering. Subtitle data/parsing is part of fframes-media.
+captions = []
exif = ["fframes-media/exif", "fframes-media-dir-macro/exif"]
compile-time-svgtree = ["svgr-macro/compile-time-svgtree"]
# `fframes::Lottie` and `frame.play_lottie`: Lottie `.json` files in the media folder
@@ -108,7 +110,7 @@ libav-agree-version3 = ["fframes-media/libav-agree-version3"]
# The codec and hardware features compile FFmpeg from source, which docs.rs cannot do (no
# network), so only the pure Rust features are documented. `--cfg fframes_docsrs` makes
# fframes-media link the FFmpeg headers of the docs.rs image instead of building FFmpeg.
-features = ["cli", "compile-time-svgtree", "exif", "3d"]
+features = ["cli", "captions", "compile-time-svgtree", "exif", "3d"]
rustc-args = ["--cfg", "fframes_docsrs"]
[lints]
diff --git a/fframes/src/audio_mix.rs b/fframes/src/audio_mix.rs
index 324333f1..2300ef9e 100644
--- a/fframes/src/audio_mix.rs
+++ b/fframes/src/audio_mix.rs
@@ -763,7 +763,7 @@ mod tests {
fn resolve_image(&'a self, _: &str) -> Option<&'a crate::media::ImageData<'a>> {
None
}
- fn resolve_subtitles(&'a self, _: &str) -> Option<&'a crate::media::Subtitles<'a>> {
+ fn resolve_subtitles(&'a self, _: &str) -> Option<&'a crate::media::Subtitles> {
None
}
fn resolve_video(&'a self, _: &str) -> Option<&'a crate::media::VideoMedia> {
diff --git a/fframes/src/captions/data.rs b/fframes/src/captions/data.rs
new file mode 100644
index 00000000..9c4a9561
--- /dev/null
+++ b/fframes/src/captions/data.rs
@@ -0,0 +1,5 @@
+//! Caption rendering uses the existing media subtitles data model.
+
+pub use crate::media::subtitles::{
+ CaptionCue, CaptionError, CaptionMetadata, CaptionTrack, CaptionWord, WordState,
+};
diff --git a/fframes/src/captions/fixtures/phrases.vtt b/fframes/src/captions/fixtures/phrases.vtt
new file mode 100644
index 00000000..90cc5b8e
--- /dev/null
+++ b/fframes/src/captions/fixtures/phrases.vtt
@@ -0,0 +1,4 @@
+WEBVTT
+
+00:00.000 --> 00:01.000
+Embedded phrase
diff --git a/fframes/src/captions/fixtures/speech.json b/fframes/src/captions/fixtures/speech.json
new file mode 100644
index 00000000..86b4ec95
--- /dev/null
+++ b/fframes/src/captions/fixtures/speech.json
@@ -0,0 +1 @@
+{"cues":[{"start":0,"end":1,"metadata":{"layout":"lower-third"},"words":[{"text":"Embedded","start":0,"end":0.5,"metadata":{"effect":"plasma","position":{"x":120,"y":80}}}]}]}
diff --git a/fframes/src/captions/mod.rs b/fframes/src/captions/mod.rs
new file mode 100644
index 00000000..60acdd49
--- /dev/null
+++ b/fframes/src/captions/mod.rs
@@ -0,0 +1,54 @@
+//! Timed captions from ordinary JSON or `WebVTT`, rendered with native SVG text.
+//!
+//! Enable the `captions` feature for rendering. The existing media [`crate::media::Subtitles`]
+//! parser accepts both JSON and `WebVTT` without that feature.
+//! Times are seconds; intervals are `[start, end)`.
+//! A cue contains either plain `text` or explicitly timed `words`. Phrase-level
+//! subtitles never receive guessed word timings.
+//! Use plain-text VTT payloads: imported markup and cue settings remain source data,
+//! rather than automatically becoming SVG styling, placement or word timings.
+//!
+//! ```no_run
+//! use fframes::captions::{CaptionTrack, Captions, CaptionMode, CaptionRect};
+//!
+//! let directory = fframes::MediaDirectory::read_folder("media")?;
+//! let media = directory.process_media_source()?;
+//! let captions = Captions::from_media(
+//! "speech.json", CaptionRect::new(100.0, 1320.0, 880.0, 360.0))
+//! .font("DM Sans", 64)
+//! .mode(CaptionMode::Highlight)
+//! .active_fill("#ffd166")
+//! .outline("#000000", 4.0);
+//! // In Video::render_frame, insert {captions.render(&mut frame, ctx)} into svgr!.
+//! // Pass `media` in RenderOptions, or embed the file with include_media_dir!.
+//! # Ok::<(), Box<dyn std::error::Error>>(())
+//! ```
+//!
+//! JSON containing `cues` is subtitle media; other JSON can be Lottie media.
+//! Both subtitle formats use the same media provider and `ctx.get_subtitles` lookup.
+//! Layout is cached by loaded track identity and rebuilt when the provider replaces it.
+//! Reconstruct the component when fonts or layout settings change.
+//! [`Captions::highlight_with`] accepts arbitrary word-local SVG for active words.
+//! [`Captions::render_with`] customizes every visible word. Callbacks can retain the
+//! preset content and use [`CaptionWordScope::mask_text`] for gradients or shader fills.
+//! JSON `metadata` objects are preserved without imposing an application schema.
+//! Call `scope.word.metadata.typed::<WordStyle>()` or
+//! `scope.cue_metadata.typed::<CueStyle>()` directly: each requested Serde type is
+//! decoded lazily once per metadata object. Successes and failures are cached
+//! independently by type and shared across clones and threads. No registration,
+//! extra media-loader configuration or per-frame JSON parsing is needed.
+//! Rendering defaults to scene time; use [`CaptionClock::Global`] for a video-wide
+//! transcript, or the explicit `render_at`/`highlight_at_with` variants for mapped time.
+//! Legacy frame phrase/cue helpers retain inclusive cue ends. This new component
+//! and [`CaptionTrack::active_cues`] use half-open intervals.
+//! [`Captions::words_at`] exposes state, progress and
+//! advance boxes for custom SVG effects. Layout uses the existing native
+//! text measurements; it does not implement general bidirectional shaping.
+
+mod data;
+mod render;
+#[cfg(test)]
+mod tests;
+
+pub use data::*;
+pub use render::*;
diff --git a/fframes/src/captions/render.rs b/fframes/src/captions/render.rs
new file mode 100644
index 00000000..886f073e
--- /dev/null
+++ b/fframes/src/captions/render.rs
@@ -0,0 +1,905 @@
+use super::{CaptionError, CaptionMetadata, CaptionTrack, WordState};
+use crate::{FFramesContext, FontQuery, Frame, Svgr, diagnostics, svgr};
+use parking_lot::Mutex;
+use std::{
+ cell::Cell,
+ collections::hash_map::DefaultHasher,
+ hash::{Hash, Hasher},
+ ops::Range,
+ sync::{
+ Arc, LazyLock,
+ atomic::{AtomicUsize, Ordering},
+ },
+};
+
+/// A rectangle in composition pixels, with a top-left origin.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct CaptionRect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
+
+impl CaptionRect {
+ pub const fn new(x: f64, y: f64, width: f64, height: f64) -> Self {
+ Self {
+ x,
+ y,
+ width,
+ height,
+ }
+ }
+}
+
+/// The same timed data can be displayed in several ways without changing its layout.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub enum CaptionMode {
+ /// Hold the whole phrase; style each word according to its timing state.
+ #[default]
+ Highlight,
+ /// Show only the active word, centered in the caption area. Gaps stay empty.
+ Word,
+ /// Reveal spoken and active words at fixed positions; upcoming words stay hidden.
+ Reveal,
+ /// Fill the active word left-to-right according to its elapsed duration.
+ Karaoke,
+}
+
+/// Scene-local time by default, matching other frame animation APIs. At video level
+/// scene and global time are equal. Use `Global` for a whole-video transcript.
+/// `words_at` and explicit render-at methods always accept track seconds.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub enum CaptionClock {
+ Global,
+ #[default]
+ Scene,
+}
+
+/// Per-word information for custom drawing. `rect` is an advance box, not glyph ink bounds.
+#[derive(Debug, Clone)]
+pub struct CaptionWordView<'a> {
+ pub text: &'a str,
+ /// Application-owned JSON metadata on the original timed word. Untimed
+ /// phrase tokens expose an empty map, without inventing per-word metadata.
+ pub metadata: &'a CaptionMetadata,
+ /// Application-owned JSON metadata on the original cue, including for
+ /// untimed phrase tokens. The caption renderer does not interpret its keys.
+ pub cue_metadata: &'a CaptionMetadata,
+ pub rect: CaptionRect,
+ pub state: WordState,
+ pub progress: f32,
+ pub cue_index: usize,
+ /// Index of this display token, including tokens in plain phrase captions.
+ pub token_index: usize,
+ /// `None` for untimed tokens of a plain phrase imported from VTT.
+ pub word_index: Option<usize>,
+ /// Track-clock seconds, or `None` for a plain phrase without word timing.
+ pub start: Option<f64>,
+ pub end: Option<f64>,
+}
+
+/// One word's drawing scope. Return any SVG from a caption rendering callback.
+///
+/// Callback drawing uses local coordinates: `(0, 0)` is the word's top-left advance
+/// box. The component applies placement afterwards. Nothing is implicitly clipped,
+/// so glows and decorations can extend outside the box. Use `clip` for a rectangular
+/// boundary or `mask_text` for the glyph silhouette.
+pub struct CaptionWordScope<'a, 'frame> {
+ /// Word metadata and a local advance rectangle whose origin is `(0, 0)`.
+ pub word: CaptionWordView<'a>,
+ /// Original cue metadata, borrowed from the same loaded track as `word`.
+ /// Read `word.metadata` for per-word effect or layout parameters.
+ pub cue_metadata: &'a CaptionMetadata,
+ /// Explicit composition placement, for inspection or advanced positioning.
+ /// Drawing returned by the callback is translated here by the component.
+ pub composition_rect: CaptionRect,
+ /// The original frame; use it for animation or `Shader::draw` without borrowing
+ /// the mutable frame passed to `render_with` again.
+ pub frame: &'frame Frame,
+ /// Caption-clock seconds (global, scene-local, or explicit render-at time).
+ pub time: f64,
+ captions: &'a Captions,
+ prefix: String,
+ next_definition: Cell<usize>,
+}
+
+impl<'a> CaptionWordScope<'a, '_> {
+ pub fn width(&self) -> f64 {
+ self.word.rect.width
+ }
+ pub fn height(&self) -> f64 {
+ self.word.rect.height
+ }
+ pub fn is_active(&self) -> bool {
+ self.word.state == WordState::Active
+ }
+
+ /// Seconds since this timed word began, clamped to zero. Plain phrases return `None`.
+ pub fn elapsed(&self) -> Option<f64> {
+ self.word.start.map(|start| (self.time - start).max(0.0))
+ }
+
+ /// An SVG-safe ID for caller-owned definitions. The same key gives the same ID
+ /// within this scope; separate tokens, components and render calls cannot collide.
+ /// IDs are internal drawing references, not persistent word identities.
+ pub fn id(&self, key: &str) -> String {
+ let mut hash = DefaultHasher::new();
+ key.hash(&mut hash);
+ format!("{}-user-{:x}", self.prefix, hash.finish())
+ }
+
+ fn definition_id(&self, kind: &str) -> String {
+ let index = self.next_definition.get();
+ self.next_definition.set(index + 1);
+ format!("{}-internal-{kind}-{index}", self.prefix)
+ }
+
+ /// Restrict any local SVG to the word's advance rectangle.
+ pub fn clip(&self, content: Svgr<'a>) -> Svgr<'a> {
+ if self.width() <= 0.0 || self.height() <= 0.0 {
+ return Svgr::empty();
+ }
+ let id = self.definition_id("clip");
+ svgr!(
+ <defs><clipPath id={id.clone()} clipPathUnits="userSpaceOnUse">
+ <rect x="0" y="0" width={self.width()} height={self.height()} />
+ </clipPath></defs>
+ <g clip-path={format!("url(#{id})")}>{content}</g>
+ )
+ }
+
+ /// Show any local SVG only through this word's glyphs, using the caption font.
+ /// This can turn a gradient, shader image or animation into a text highlight.
+ pub fn mask_text(&self, content: Svgr<'a>) -> Svgr<'a> {
+ if self.width() <= 0.0 || self.height() <= 0.0 {
+ return Svgr::empty();
+ }
+ let id = self.definition_id("mask");
+ let mut local = self.word.clone();
+ local.rect.x = 0.0;
+ local.rect.y = 0.0;
+ let glyphs = self.captions.text(&local, "white", false);
+ // Leave room for glyph overhangs; the mask content is still the exact glyph
+ // silhouette. An advance box is not a tight ink bounding box.
+ let padding = self.captions.font_size as f64;
+ svgr!(
+ <defs><mask id={id.clone()} maskUnits="userSpaceOnUse" maskContentUnits="userSpaceOnUse"
+ mask-type="alpha" x={-padding} y={-padding}
+ width={self.width() + padding * 2.0} height={self.height() + padding * 2.0}>
+ {glyphs}
+ </mask></defs>
+ <g mask={format!("url(#{id})")}>{content}</g>
+ )
+ }
+}
+
+#[derive(Debug)]
+struct PreparedWord {
+ token: PreparedToken,
+ rect: CaptionRect,
+}
+
+#[derive(Debug)]
+enum PreparedToken {
+ Word(usize),
+ Text(Range<usize>),
+}
+
+#[derive(Debug)]
+struct PreparedCue {
+ words: Vec<PreparedWord>,
+ height: f64,
+}
+
+#[derive(Debug)]
+struct PreparedTrack {
+ identity: Arc<()>,
+ cues: Vec<PreparedCue>,
+ inner: CaptionRect,
+}
+
+#[derive(Debug)]
+enum CaptionSource {
+ Owned(CaptionTrack),
+ Media(String),
+}
+
+/// An immutable caption component. Create once, render at any frame and in any order.
+///
+/// Font resolution and word layout are cached after their first successful evaluation.
+/// Named media is resolved from the context and the cache follows loaded track revisions.
+/// Missing fonts and overflow are reported through frame diagnostics by `render`; use
+/// `try_render` or `words_at` when the caller wants an explicit error.
+#[derive(Debug)]
+pub struct Captions {
+ source: CaptionSource,
+ font: String,
+ font_size: usize,
+ font_weight: u16,
+ bounds: CaptionRect,
+ mode: CaptionMode,
+ clock: CaptionClock,
+ upcoming: String,
+ active: String,
+ spoken: String,
+ outline: Option<(String, f64)>,
+ background: Option<(String, f64)>,
+ underline: Option<(String, f64)>,
+ line_height: f64,
+ layout: Mutex<Option<PreparedTrack>>,
+ id: usize,
+}
+
+static NEXT_COMPONENT: AtomicUsize = AtomicUsize::new(0);
+static NEXT_RENDER: AtomicUsize = AtomicUsize::new(0);
+static EMPTY_METADATA: LazyLock<CaptionMetadata> = LazyLock::new(CaptionMetadata::new);
+
+impl Captions {
+ pub fn new(track: CaptionTrack, bounds: CaptionRect) -> Self {
+ Self::with_source(CaptionSource::Owned(track), bounds)
+ }
+
+ /// Use a caption track loaded by the `FFrames` media provider, like images or audio.
+ /// The same component follows a newly loaded revision under the same media name.
+ pub fn from_media(name: impl Into<String>, bounds: CaptionRect) -> Self {
+ Self::with_source(CaptionSource::Media(name.into()), bounds)
+ }
+
+ fn with_source(source: CaptionSource, bounds: CaptionRect) -> Self {
+ Self {
+ source,
+ font: "DM Sans".into(),
+ font_size: 64,
+ font_weight: 600,
+ bounds,
+ mode: CaptionMode::default(),
+ clock: CaptionClock::default(),
+ upcoming: "#aeb4c0".into(),
+ active: "#ffd166".into(),
+ spoken: "#ffffff".into(),
+ outline: Some(("#000000".into(), 3.0)),
+ background: None,
+ underline: None,
+ line_height: 1.25,
+ layout: Mutex::new(None),
+ id: NEXT_COMPONENT.fetch_add(1, Ordering::Relaxed),
+ }
+ }
+
+ /// Resolve the current track from its configured source.
+ pub fn track<'a, 'ctx, 'media: 'a>(
+ &'a self,
+ ctx: &FFramesContext<'ctx, 'media>,
+ ) -> Result<&'a CaptionTrack, CaptionError> {
+ match &self.source {
+ CaptionSource::Owned(track) => Ok(track),
+ CaptionSource::Media(name) => ctx.get_subtitles(name).ok_or_else(|| {
+ CaptionError::invalid(
+ format!("media.{name}"),
+ "caption track is not loaded; add it through the FFrames media provider",
+ )
+ }),
+ }
+ }
+
+ pub fn font(mut self, family: impl Into<String>, size: usize) -> Self {
+ self.font = family.into();
+ self.font_size = size;
+ self.layout.get_mut().take();
+ self
+ }
+ pub fn font_weight(mut self, weight: u16) -> Self {
+ self.font_weight = weight;
+ self.layout.get_mut().take();
+ self
+ }
+ /// Change the logical bounds supplied at construction. The text sits at the bottom of this
+ /// area; overlapping cues stack vertically. Draft output scaling does not change it.
+ pub fn bounds(mut self, bounds: CaptionRect) -> Self {
+ self.bounds = bounds;
+ self.layout.get_mut().take();
+ self
+ }
+ pub fn line_height(mut self, multiplier: f64) -> Self {
+ self.line_height = multiplier;
+ self.layout.get_mut().take();
+ self
+ }
+ pub fn mode(mut self, mode: CaptionMode) -> Self {
+ self.mode = mode;
+ self.layout.get_mut().take();
+ self
+ }
+ pub fn clock(mut self, clock: CaptionClock) -> Self {
+ self.clock = clock;
+ self
+ }
+ pub fn active_fill(mut self, fill: impl Into<String>) -> Self {
+ self.active = fill.into();
+ self
+ }
+ pub fn upcoming_fill(mut self, fill: impl Into<String>) -> Self {
+ self.upcoming = fill.into();
+ self
+ }
+ pub fn spoken_fill(mut self, fill: impl Into<String>) -> Self {
+ self.spoken = fill.into();
+ self
+ }
+ pub fn outline(mut self, fill: impl Into<String>, width: f64) -> Self {
+ self.outline = Some((fill.into(), width));
+ self.layout.get_mut().take();
+ self
+ }
+ pub fn active_background(mut self, fill: impl Into<String>, padding: f64) -> Self {
+ self.background = Some((fill.into(), padding));
+ self.layout.get_mut().take();
+ self
+ }
+ pub fn underline(mut self, fill: impl Into<String>, width: f64) -> Self {
+ self.underline = Some((fill.into(), width));
+ self.layout.get_mut().take();
+ self
+ }
+
+ fn font_query(&self) -> FontQuery<'_> {
+ FontQuery {
+ family: &self.font,
+ size: self.font_size,
+ weight: self.font_weight,
+ ..Default::default()
+ }
+ }
+
+ fn prepare(
+ &self,
+ track: &CaptionTrack,
+ _frame: &mut Frame,
+ ctx: &FFramesContext<'_, '_>,
+ ) -> Result<PreparedTrack, CaptionError> {
+ if self.font_size == 0 || !self.line_height.is_finite() || self.line_height < 1.0 {
+ return Err(CaptionError::invalid(
+ "layout.font",
+ "font size must be positive and line_height must be finite and >= 1",
+ ));
+ }
+ let mut inset: f64 = 0.0;
+ for (name, setting) in [
+ ("outline", &self.outline),
+ ("background", &self.background),
+ ("underline", &self.underline),
+ ] {
+ if let Some((_, size)) = setting {
+ if !size.is_finite() || *size < 0.0 {
+ return Err(CaptionError::invalid(
+ format!("style.{name}"),
+ "size must be finite and nonnegative",
+ ));
+ }
+ inset = inset.max(*size);
+ }
+ }
+ let bounds = self.bounds;
+ if ![bounds.x, bounds.y, bounds.width, bounds.height]
+ .into_iter()
+ .all(f64::is_finite)
+ || bounds.width <= inset * 2.0
+ || bounds.height <= inset * 2.0
+ {
+ return Err(CaptionError::invalid(
+ "layout.bounds",
+ "bounds must be finite and have room for text and effects",
+ ));
+ }
+ let inner = CaptionRect::new(
+ bounds.x + inset,
+ bounds.y + inset,
+ bounds.width - inset * 2.0,
+ bounds.height - inset * 2.0,
+ );
+ let font_source = ctx.font_source.ok_or_else(|| {
+ CaptionError::invalid("layout.font", "caption layout needs a font source")
+ })?;
+ let measure = |text: &str| {
+ crate::text_get_width_impl(self.font_query(), text, font_source)
+ .map(|width| width as f64)
+ .ok_or_else(|| {
+ CaptionError::invalid(
+ "layout.font",
+ format!(
+ "cannot measure font {:?}; load this font in the media provider",
+ self.font
+ ),
+ )
+ })
+ };
+ let space = measure(" ")?;
+ let line_height = self.font_size as f64 * self.line_height;
+ let mut cues = Vec::with_capacity(track.cues().len());
+ for (cue_index, cue) in track.cues().iter().enumerate() {
+ let tokens: Vec<(&str, PreparedToken, bool, bool)> = if cue.words.is_empty() {
+ cue.text
+ .lines()
+ .enumerate()
+ .flat_map(|(line_index, line)| {
+ line.split_whitespace()
+ .enumerate()
+ .map(move |(index, text)| {
+ let start = text.as_ptr() as usize - cue.text.as_ptr() as usize;
+ (
+ text,
+ PreparedToken::Text(start..start + text.len()),
+ true,
+ line_index > 0 && index == 0,
+ )
+ })
+ })
+ .collect()
+ } else {
+ cue.words
+ .iter()
+ .enumerate()
+ .map(|(i, word)| {
+ (
+ word.text.as_str(),
+ PreparedToken::Word(i),
+ word.space_before,
+ false,
+ )
+ })
+ .collect()
+ };
+ let mut lines: Vec<(Vec<PreparedWord>, f64)> = vec![(Vec::new(), 0.0)];
+ for (text, token, space_before, break_before) in tokens {
+ let width = measure(text)?;
+ if width > inner.width {
+ return Err(CaptionError::invalid(
+ format!("cues[{cue_index}].layout"),
+ format!(
+ "word {text:?} exceeds caption width; increase width or reduce font size"
+ ),
+ ));
+ }
+ if break_before && !lines[lines.len() - 1].0.is_empty() {
+ lines.push((Vec::new(), 0.0));
+ }
+ let last_index = lines.len() - 1;
+ let (line, line_width) = &mut lines[last_index];
+ let separator = if line.is_empty() || !space_before {
+ 0.0
+ } else {
+ space
+ };
+ if !line.is_empty() && *line_width + separator + width > inner.width {
+ lines.push((
+ vec![PreparedWord {
+ token,
+ rect: CaptionRect::new(0.0, 0.0, width, line_height),
+ }],
+ width,
+ ));
+ } else {
+ line.push(PreparedWord {
+ token,
+ rect: CaptionRect::new(*line_width + separator, 0.0, width, line_height),
+ });
+ *line_width += separator + width;
+ }
+ }
+ let height = lines.len() as f64 * line_height;
+ let displayed_height = if self.mode == CaptionMode::Word && !cue.words.is_empty() {
+ line_height
+ } else {
+ height
+ };
+ if displayed_height > inner.height {
+ return Err(CaptionError::invalid(
+ format!("cues[{cue_index}].layout"),
+ "wrapped phrase exceeds caption height; enlarge the area or reduce font size",
+ ));
+ }
+ let words = lines
+ .into_iter()
+ .enumerate()
+ .flat_map(|(line_index, (words, width))| {
+ words.into_iter().map(move |mut word| {
+ word.rect.x += (inner.width - width) / 2.0;
+ word.rect.y = line_index as f64 * line_height;
+ word
+ })
+ })
+ .collect();
+ cues.push(PreparedCue { words, height });
+ }
+ Ok(PreparedTrack {
+ identity: track.cache_identity().clone(),
+ cues,
+ inner,
+ })
+ }
+
+ /// Word state and positioned advance boxes at explicit track seconds. The full phrase
+ /// is laid out once, so changing active words cannot make other words move.
+ pub fn words_at<'a, 'ctx, 'media: 'a>(
+ &'a self,
+ seconds: f64,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ ) -> Result<Vec<CaptionWordView<'a>>, CaptionError> {
+ if !seconds.is_finite() {
+ return Err(CaptionError::invalid("time", "seconds must be finite"));
+ }
+ let track = self.track(ctx)?;
+ let active: Vec<_> = track.active_cues(seconds).collect();
+ if active.is_empty() {
+ return Ok(Vec::new());
+ }
+ let mut cached = self.layout.lock();
+ if cached
+ .as_ref()
+ .is_none_or(|layout| !Arc::ptr_eq(&layout.identity, track.cache_identity()))
+ {
+ // Failed preparation leaves any previous revision intact and retries next time.
+ // The identity token stays allocated with the cached layout, preventing reuse.
+ let prepared = self.prepare(track, frame, ctx)?;
+ *cached = Some(prepared);
+ }
+ let layout = cached
+ .as_ref()
+ .ok_or_else(|| CaptionError::invalid("layout", "layout preparation failed"))?;
+ let height = |index: usize| {
+ if self.mode == CaptionMode::Word && !track.cues()[index].words.is_empty() {
+ self.font_size as f64 * self.line_height
+ } else {
+ layout.cues[index].height
+ }
+ };
+ let gap = self.font_size as f64 * 0.3;
+ let total = active.iter().map(|(i, _)| height(*i)).sum::<f64>()
+ + active.len().saturating_sub(1) as f64 * gap;
+ if total > layout.inner.height {
+ return Err(CaptionError::invalid(
+ "layout.overlap",
+ "simultaneous cues exceed caption height; enlarge the area or use separate components",
+ ));
+ }
+ let mut top = layout.inner.y + layout.inner.height - total;
+ let mut views = Vec::new();
+ for (cue_index, cue) in active {
+ let single_word = self.mode == CaptionMode::Word && !cue.words.is_empty();
+ for (token_index, word) in layout.cues[cue_index].words.iter().enumerate() {
+ let (text, word_index) = match &word.token {
+ PreparedToken::Word(index) => (cue.words[*index].text.as_str(), Some(*index)),
+ PreparedToken::Text(range) => (&cue.text[range.clone()], None),
+ };
+ let (state, progress) = word_index.map_or((WordState::Spoken, 1.0), |index| {
+ (
+ cue.words[index].state_at(seconds),
+ cue.words[index].progress_at(seconds),
+ )
+ });
+ if single_word && state != WordState::Active {
+ continue;
+ }
+ let rect = if single_word {
+ CaptionRect::new(
+ layout.inner.x + (layout.inner.width - word.rect.width) / 2.0,
+ top,
+ word.rect.width,
+ word.rect.height,
+ )
+ } else {
+ CaptionRect::new(
+ layout.inner.x + word.rect.x,
+ top + word.rect.y,
+ word.rect.width,
+ word.rect.height,
+ )
+ };
+ views.push(CaptionWordView {
+ text,
+ metadata: word_index
+ .map_or(&EMPTY_METADATA, |index| &cue.words[index].metadata),
+ cue_metadata: &cue.metadata,
+ rect,
+ state,
+ progress,
+ cue_index,
+ token_index,
+ word_index,
+ start: word_index.map(|index| cue.words[index].start),
+ end: word_index.map(|index| cue.words[index].end),
+ });
+ }
+ top += height(cue_index) + gap;
+ }
+ Ok(views)
+ }
+
+ /// Render using the selected global or scene clock; errors become inspection findings.
+ pub fn render<'a, 'ctx, 'media: 'a>(
+ &'a self,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ ) -> Svgr<'a> {
+ match self.try_render(frame, ctx) {
+ Ok(svg) => svg,
+ Err(error) => {
+ diagnostics::report(diagnostics::Diagnostic::CaptionError {
+ message: error.to_string(),
+ });
+ Svgr::empty()
+ }
+ }
+ }
+
+ pub fn try_render<'a, 'ctx, 'media: 'a>(
+ &'a self,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ ) -> Result<Svgr<'a>, CaptionError> {
+ self.try_render_with(frame, ctx, |_, content| content)
+ }
+
+ /// Use explicit track seconds, for example after mapping from a source clock.
+ pub fn try_render_at<'a, 'ctx, 'media: 'a>(
+ &'a self,
+ seconds: f64,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ ) -> Result<Svgr<'a>, CaptionError> {
+ self.try_render_at_with(seconds, frame, ctx, |_, content| content)
+ }
+
+ /// Render at explicit track seconds; errors become inspection findings.
+ pub fn render_at<'a, 'ctx, 'media: 'a>(
+ &'a self,
+ seconds: f64,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ ) -> Svgr<'a> {
+ report_render_result(self.try_render_at(seconds, frame, ctx))
+ }
+
+ /// Customize every visible word at explicit track seconds.
+ pub fn render_at_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ seconds: f64,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ render_word: F,
+ ) -> Svgr<'a>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ report_render_result(self.try_render_at_with(seconds, frame, ctx, render_word))
+ }
+
+ /// Customize active words at explicit track seconds. Other words keep their preset SVG.
+ pub fn highlight_at_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ seconds: f64,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ highlight: F,
+ ) -> Svgr<'a>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ report_render_result(self.try_highlight_at_with(seconds, frame, ctx, highlight))
+ }
+
+ pub fn try_highlight_at_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ seconds: f64,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ mut highlight: F,
+ ) -> Result<Svgr<'a>, CaptionError>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ self.try_render_at_with(seconds, frame, ctx, |scope, content| {
+ if scope.is_active() {
+ highlight(scope, content)
+ } else {
+ content
+ }
+ })
+ }
+
+ /// Customize every visible word. The callback returns SVG in word-local coordinates.
+ /// The second argument owns the preset SVG; return it or compose it without cloning.
+ /// `Word` and `Reveal` modes
+ /// filter invisible words before invoking the callback. The callback is never stored.
+ pub fn render_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ render_word: F,
+ ) -> Svgr<'a>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ match self.try_render_with(frame, ctx, render_word) {
+ Ok(svg) => svg,
+ Err(error) => {
+ diagnostics::report(diagnostics::Diagnostic::CaptionError {
+ message: error.to_string(),
+ });
+ Svgr::empty()
+ }
+ }
+ }
+
+ pub fn try_render_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ render_word: F,
+ ) -> Result<Svgr<'a>, CaptionError>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ if frame.fps == 0 {
+ return Err(CaptionError::invalid("clock.fps", "FPS must be positive"));
+ }
+ let index = match self.clock {
+ CaptionClock::Global => frame.global_index,
+ CaptionClock::Scene => frame.index,
+ };
+ self.try_render_at_with(index as f64 / frame.fps as f64, frame, ctx, render_word)
+ }
+
+ /// Customize only active timed words. Other visible words retain their preset drawing.
+ /// No highlight callback runs in a speech gap or for untimed phrase text.
+ pub fn highlight_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ highlight: F,
+ ) -> Svgr<'a>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ match self.try_highlight_with(frame, ctx, highlight) {
+ Ok(svg) => svg,
+ Err(error) => {
+ diagnostics::report(diagnostics::Diagnostic::CaptionError {
+ message: error.to_string(),
+ });
+ Svgr::empty()
+ }
+ }
+ }
+
+ pub fn try_highlight_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ mut highlight: F,
+ ) -> Result<Svgr<'a>, CaptionError>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ self.try_render_with(frame, ctx, |scope, content| {
+ if scope.is_active() {
+ highlight(scope, content)
+ } else {
+ content
+ }
+ })
+ }
+
+ /// Custom drawing at explicit caption-clock seconds, for mapped source timing.
+ pub fn try_render_at_with<'a, 'ctx, 'media: 'a, F>(
+ &'a self,
+ seconds: f64,
+ frame: &mut Frame,
+ ctx: &FFramesContext<'ctx, 'media>,
+ mut render_word: F,
+ ) -> Result<Svgr<'a>, CaptionError>
+ where
+ F: for<'frame> FnMut(&CaptionWordScope<'a, 'frame>, Svgr<'a>) -> Svgr<'a>,
+ {
+ // words_at releases its layout lock before the callback can execute or re-enter.
+ let words = self.words_at(seconds, frame, ctx)?;
+ let invocation = NEXT_RENDER.fetch_add(1, Ordering::Relaxed);
+ Ok(words
+ .into_iter()
+ .filter(|word| self.mode != CaptionMode::Reveal || word.state != WordState::Upcoming)
+ .map(|word| {
+ let prefix = format!(
+ "caption-{}-{invocation}-{}-{}",
+ self.id, word.cue_index, word.token_index
+ );
+ let mut local = word.clone();
+ local.rect.x = 0.0;
+ local.rect.y = 0.0;
+ let content = self.draw_word(&local, format!("{prefix}-preset-karaoke"));
+ let x = word.rect.x;
+ let y = word.rect.y;
+ let scope = CaptionWordScope {
+ cue_metadata: word.cue_metadata,
+ word: local,
+ composition_rect: word.rect,
+ frame,
+ time: seconds,
+ captions: self,
+ prefix,
+ next_definition: Cell::new(0),
+ };
+ let svg = render_word(&scope, content);
+ svgr!(<g transform={format!("translate({x} {y})")}>{svg}</g>)
+ })
+ .collect())
+ }
+
+ fn text<'a>(&'a self, word: &CaptionWordView<'a>, fill: &'a str, outlined: bool) -> Svgr<'a> {
+ let (stroke, width) = if outlined {
+ self.outline
+ .as_ref()
+ .map_or(("none", 0.0), |(fill, width)| (fill.as_str(), *width))
+ } else {
+ ("none", 0.0)
+ };
+ svgr!(<text x={word.rect.x} y={word.rect.y + self.font_size as f64}
+ font-family={self.font.as_str()} font-size={self.font_size} font-weight={self.font_weight}
+ fill={fill} stroke={stroke} stroke-width={width} stroke-linejoin="round" paint-order="stroke fill"
+ >{word.text}</text>)
+ }
+
+ fn draw_word<'a>(&'a self, word: &CaptionWordView<'a>, karaoke_id: String) -> Svgr<'a> {
+ let fill = match word.state {
+ WordState::Upcoming => self.upcoming.as_str(),
+ WordState::Active => self.active.as_str(),
+ WordState::Spoken => self.spoken.as_str(),
+ };
+ let mut nodes = Vec::new();
+ if word.state == WordState::Active
+ && word.rect.width > 0.0
+ && let Some((fill, padding)) = &self.background
+ {
+ nodes.push(
+ svgr!(<rect x={word.rect.x - padding} y={word.rect.y - padding}
+ width={word.rect.width + padding * 2.0} height={word.rect.height + padding * 2.0}
+ rx={padding} fill={fill.as_str()} />),
+ );
+ }
+ if self.mode == CaptionMode::Karaoke && word.state == WordState::Active {
+ nodes.push(self.text(word, &self.upcoming, true));
+ if word.progress > 0.0 && word.rect.width > 0.0 {
+ let id = karaoke_id;
+ let text = self.text(word, &self.active, false);
+ nodes.push(svgr!(
+ <defs><clipPath id={id.clone()}><rect x={word.rect.x} y={word.rect.y - 4.0}
+ width={word.rect.width * f64::from(word.progress)} height={word.rect.height + 8.0} /></clipPath></defs>
+ <g clip-path={format!("url(#{id})")}>{text}</g>
+ ));
+ }
+ } else {
+ nodes.push(self.text(word, fill, true));
+ }
+ if word.state == WordState::Active
+ && word.rect.width > 0.0
+ && let Some((fill, width)) = &self.underline
+ && *width > 0.0
+ {
+ nodes.push(
+ svgr!(<rect x={word.rect.x} y={word.rect.y + self.font_size as f64 + 2.0}
+ width={word.rect.width} height={*width} fill={fill.as_str()} />),
+ );
+ }
+ nodes.into_iter().collect()
+ }
+}
+
+fn report_render_result(result: Result<Svgr<'_>, CaptionError>) -> Svgr<'_> {
+ result.unwrap_or_else(|error| {
+ diagnostics::report(diagnostics::Diagnostic::CaptionError {
+ message: error.to_string(),
+ });
+ Svgr::empty()
+ })
+}
diff --git a/fframes/src/captions/tests.rs b/fframes/src/captions/tests.rs
new file mode 100644
index 00000000..1a44b304
--- /dev/null
+++ b/fframes/src/captions/tests.rs
@@ -0,0 +1,290 @@
+use super::*;
+use crate::{
+ DynamicMediaProvider, FFramesContext, FFramesMode, FontFace, FontSource, FontStretch,
+ FontStyle, Frame, MediaProvider, TimeBase, VideoSize,
+};
+use std::sync::{
+ Arc,
+ atomic::{AtomicUsize, Ordering},
+};
+
+#[derive(Debug)]
+struct Face;
+impl FontFace<'_> for Face {
+ fn is_monospaced(&self) -> Option<bool> {
+ Some(true)
+ }
+ fn resolve_char_width(&self, _: usize, _: char) -> Option<usize> {
+ Some(10)
+ }
+}
+
+#[derive(Debug, Default)]
+struct Fonts(AtomicUsize);
+impl<'a> FontSource<'a> for Fonts {
+ fn add_font(&mut self, _: String, _: Arc<dyn AsRef<[u8]> + Send + Sync>) {}
+ fn resolve_font(
+ &'a self,
+ _: &str,
+ _: u16,
+ _: FontStyle,
+ _: FontStretch,
+ ) -> Option<Box<dyn FontFace<'a> + 'a>> {
+ self.0.fetch_add(1, Ordering::Relaxed);
+ Some(Box::new(Face))
+ }
+}
+
+fn context<'a>(
+ fonts: Option<&'a Fonts>,
+ media: Option<&'a dyn MediaProvider<'a>>,
+) -> FFramesContext<'a, 'a> {
+ FFramesContext {
+ time_base: TimeBase {
+ fps: 10,
+ sample_rate: 48_000,
+ },
+ current_video_size: VideoSize {
+ width: 320,
+ height: 180,
+ },
+ duration_in_frames: 30,
+ mode: FFramesMode::Renderer,
+ scenes: None,
+ media_source: media,
+ font_source: fonts.map(|f| f as &dyn FontSource<'_>),
+ abort_signal: None,
+ }
+}
+
+fn track() -> CaptionTrack {
+ CaptionTrack::new([CaptionCue::words(
+ 0.0,
+ 2.0,
+ [
+ CaptionWord::new("Hello", 0.0, 0.5),
+ CaptionWord::new("world", 1.0, 1.5),
+ ],
+ )])
+ .unwrap()
+}
+
+fn captions() -> Captions {
+ Captions::from_media("speech.json", CaptionRect::new(10.0, 20.0, 200.0, 100.0)).font("Test", 10)
+}
+
+#[test]
+fn frames_and_seeks_reuse_layout_but_new_media_invalidates_it() {
+ let fonts = Fonts::default();
+ let mut media = DynamicMediaProvider::default().with_subtitles("speech.json", track());
+ let component = captions();
+ let mut frame = Frame::new(0, 0, 10);
+ let initial = component
+ .words_at(0.25, &mut frame, &context(Some(&fonts), Some(&media)))
+ .unwrap();
+ let positions: Vec<_> = initial.iter().map(|w| w.rect).collect();
+ assert_eq!(initial[0].state, WordState::Active);
+ assert_eq!(initial[0].progress, 0.5);
+ drop(initial);
+ let measured = fonts.0.load(Ordering::Relaxed);
+ assert!(measured > 0);
+ for time in [1.25, 0.0, 0.75, 1.5, 0.25] {
+ let words = component
+ .words_at(time, &mut frame, &context(Some(&fonts), Some(&media)))
+ .unwrap();
+ assert_eq!(words.iter().map(|w| w.rect).collect::<Vec<_>>(), positions);
+ }
+ assert_eq!(fonts.0.load(Ordering::Relaxed), measured);
+ media = media.with_subtitles(
+ "speech.json",
+ CaptionTrack::new([CaptionCue::text(0.0, 2.0, "Replaced")]).unwrap(),
+ );
+ let words = component
+ .words_at(0.25, &mut frame, &context(Some(&fonts), Some(&media)))
+ .unwrap();
+ assert_eq!(words[0].text, "Replaced");
+ assert!(fonts.0.load(Ordering::Relaxed) > measured);
+}
+
+#[test]
+fn highlights_run_only_for_active_words_and_keep_scoped_metadata() {
+ #[derive(serde::Deserialize, PartialEq, Debug)]
+ #[serde(rename_all = "kebab-case")]
+ enum Effect {
+ Outline,
+ }
+ #[derive(serde::Deserialize)]
+ struct Style {
+ effect: Effect,
+ }
+ let track = CaptionTrack::parse(
+ r#"{"cues":[{"start":0,"end":2,"metadata":{"speaker":"A"},"words":[{"text":"Moon","start":0.5,"end":1,"metadata":{"effect":"outline"}}]}]}"#,
+ ).unwrap();
+ let media = DynamicMediaProvider::default().with_subtitles("speech.json", track);
+ let fonts = Fonts::default();
+ let ctx = context(Some(&fonts), Some(&media));
+ let component = captions();
+ for (index, expected_calls) in [(0, 0), (5, 1), (9, 1), (10, 0), (20, 0)] {
+ let mut frame = Frame::new(index, index, 10);
+ let mut calls = 0;
+ component
+ .try_highlight_with(&mut frame, &ctx, |scope, content| {
+ calls += 1;
+ assert_eq!(
+ scope.word.metadata.typed::<Style>().unwrap().effect,
+ Effect::Outline
+ );
+ assert_eq!(scope.cue_metadata["speaker"], "A");
+ assert_eq!(scope.word.rect.width, 40.0);
+ assert_eq!((scope.word.rect.x, scope.word.rect.y), (0.0, 0.0));
+ assert!(scope.composition_rect.x >= 10.0);
+ assert!(scope.composition_rect.y >= 20.0);
+ scope.mask_text(content)
+ })
+ .unwrap();
+ assert_eq!(calls, expected_calls);
+ }
+}
+
+#[test]
+fn modes_use_the_selected_clock_and_scope_svg_definitions() {
+ let media = DynamicMediaProvider::default().with_subtitles("speech.json", track());
+ let fonts = Fonts::default();
+ let ctx = context(Some(&fonts), Some(&media));
+ let mut definitions = std::collections::HashSet::new();
+ let default_component = captions();
+ let mut frame = Frame::new(2, 12, 10);
+ let mut active = Vec::new();
+ default_component.highlight_with(&mut frame, &ctx, |scope, text| {
+ active.push(scope.word.text);
+ scope.mask_text(text)
+ });
+ assert_eq!(active, ["Hello"], "the default clock must be scene-local");
+ active.clear();
+ default_component.highlight_at_with(1.2, &mut frame, &ctx, |scope, text| {
+ active.push(scope.word.text);
+ assert_eq!(scope.time, 1.2);
+ scope.mask_text(text)
+ });
+ assert_eq!(
+ active,
+ ["world"],
+ "explicit time must override the frame clock"
+ );
+ let (_, findings) =
+ crate::diagnostics::collect(|| default_component.render_at(1.2, &mut frame, &ctx));
+ assert_eq!(findings.len(), 0, "{findings:?}");
+ for (clock, active) in [
+ (CaptionClock::Global, "world"),
+ (CaptionClock::Scene, "Hello"),
+ ] {
+ for mode in [
+ CaptionMode::Highlight,
+ CaptionMode::Word,
+ CaptionMode::Reveal,
+ CaptionMode::Karaoke,
+ ] {
+ let component = captions().clock(clock).mode(mode);
+ // The local scene is at 0.2s; the composition is at 1.2s.
+ let mut frame = Frame::new(2, 12, 10);
+ for _ in 0..2 {
+ let mut visible = Vec::new();
+ let mut highlighted = Vec::new();
+ component
+ .try_render_with(&mut frame, &ctx, |scope, content| {
+ let id = scope.id("paint");
+ assert_eq!(id, scope.id("paint"));
+ assert!(definitions.insert(id), "SVG IDs collided across scopes");
+ visible.push(scope.word.text);
+ if scope.is_active() {
+ highlighted.push(scope.word.text);
+ }
+ content
+ })
+ .unwrap();
+ assert_eq!(highlighted, [active]);
+ let expected = if mode == CaptionMode::Word {
+ vec![active]
+ } else if mode == CaptionMode::Reveal && clock == CaptionClock::Scene {
+ vec!["Hello"]
+ } else {
+ vec!["Hello", "world"]
+ };
+ assert_eq!(visible, expected);
+ }
+ }
+ }
+}
+
+#[test]
+fn legacy_frame_helpers_keep_the_last_cue_frame() {
+ let track =
+ CaptionTrack::parse("WEBVTT\n\n00:01.200 --> 00:03.000\nKeep the last frame\n").unwrap();
+ let end = Frame::new(90, 90, 30);
+ assert_eq!(end.get_subtitle_phrase(&track), Some("Keep the last frame"));
+ assert!(end.get_subtitle_cue(&track).is_some());
+ assert!(Frame::new(91, 91, 30).get_subtitle_cue(&track).is_none());
+ assert_eq!(Frame::new(36, 36, 30).get_cue_stack(&track, 0).len(), 0);
+ assert_eq!(track.active_cues(3.0).count(), 0);
+}
+
+#[test]
+fn missing_fonts_can_recover_and_bad_layout_is_reported() {
+ let media = DynamicMediaProvider::default().with_subtitles("speech.json", track());
+ let mut frame = Frame::new(0, 0, 10);
+ let component = captions();
+ assert!(
+ component
+ .words_at(0.0, &mut frame, &context(None, Some(&media)))
+ .is_err()
+ );
+ let fonts = Fonts::default();
+ let ctx = context(Some(&fonts), Some(&media));
+ assert_eq!(component.words_at(0.0, &mut frame, &ctx).unwrap().len(), 2);
+ let too_small =
+ Captions::new(track(), CaptionRect::new(0.0, 0.0, 20.0, 100.0)).font("Test", 10);
+ let (_, findings) = crate::diagnostics::collect(|| too_small.render(&mut frame, &ctx));
+ assert!(
+ findings
+ .iter()
+ .any(|f| matches!(f, crate::diagnostics::Diagnostic::CaptionError { .. }))
+ );
+}
+
+crate::include_media_dir!(struct Embedded, "fframes/src/captions/fixtures");
+
+#[test]
+fn runtime_and_embedded_subtitles_use_the_same_provider_contract() {
+ #[derive(serde::Deserialize)]
+ struct Style {
+ effect: String,
+ }
+ let embedded = Embedded::new().unwrap();
+ let directory = crate::MediaDirectory::read_folder(concat!(
+ env!("CARGO_MANIFEST_DIR"),
+ "/src/captions/fixtures"
+ ))
+ .unwrap();
+ let runtime = directory.process_media_source().unwrap();
+ for provider in [&embedded as &dyn MediaProvider<'_>, &runtime] {
+ let subtitles = provider.resolve_subtitles("speech.json").unwrap();
+ assert_eq!(
+ subtitles.cues()[0].words[0]
+ .metadata
+ .typed::<Style>()
+ .unwrap()
+ .effect,
+ "plasma"
+ );
+ assert_eq!(
+ provider.resolve_subtitles("phrases.vtt").unwrap().cues()[0].phrase(),
+ "Embedded phrase"
+ );
+ assert_eq!(provider.get_all_subtitle_data().len(), 2);
+ }
+ let cloned = runtime.clone();
+ assert!(std::ptr::eq(
+ runtime.resolve_subtitles("speech.json").unwrap().cues(),
+ cloned.resolve_subtitles("speech.json").unwrap().cues()
+ ));
+}
diff --git a/fframes/src/diagnostics.rs b/fframes/src/diagnostics.rs
index 8f460a39..04575251 100644
--- a/fframes/src/diagnostics.rs
+++ b/fframes/src/diagnostics.rs
@@ -37,6 +37,8 @@ pub enum MediaKind {
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Diagnostic {
+ /// A caption cannot be laid out or rendered with the requested settings.
+ CaptionError { message: String },
/// `ctx.get_image/get_audio/get_video/get_subtitles` did not find the file.
MissingMedia { media: MediaKind, name: String },
/// No font in the database matches the requested family, the text is drawn with a fallback.
@@ -70,6 +72,7 @@ impl Diagnostic {
pub fn severity(&self) -> Severity {
match self {
Diagnostic::Panic { .. }
+ | Diagnostic::CaptionError { .. }
| Diagnostic::MissingMedia { .. }
| Diagnostic::MissingGlyph { .. }
| Diagnostic::InvalidTransform { .. } => Severity::Error,
@@ -94,6 +97,7 @@ impl std::fmt::Display for Diagnostic {
write!(f, "{media:?} \"{name}\" is not in the media provider")
}
Diagnostic::MissingFont { message }
+ | Diagnostic::CaptionError { message }
| Diagnostic::MissingGlyph { message }
| Diagnostic::RendererWarning { message } => write!(f, "{message}"),
Diagnostic::TextClipped { text, .. } => write!(
diff --git a/fframes/src/fframes_context.rs b/fframes/src/fframes_context.rs
index a6788acc..d46613ca 100644
--- a/fframes/src/fframes_context.rs
+++ b/fframes/src/fframes_context.rs
@@ -69,7 +69,7 @@ impl<'a, 'media: 'a> FFramesContext<'a, 'media> {
audio
}
- pub fn get_subtitles(&self, filename: impl AsRef<str>) -> Option<&'media Subtitles<'media>> {
+ pub fn get_subtitles(&self, filename: impl AsRef<str>) -> Option<&'media Subtitles> {
let filename = filename.as_ref();
let subtitles = self
.media_source
diff --git a/fframes/src/frame.rs b/fframes/src/frame.rs
index dab6d2ce..fddb71cb 100644
--- a/fframes/src/frame.rs
+++ b/fframes/src/frame.rs
@@ -411,6 +411,7 @@ impl Frame {
}
/// Returns a cue that must be rendered by the time of the current frame
+ /// Legacy lookup includes the cue's ending timestamp.
/// Besides text cue contains additional metadata like start/end time stamp,
/// notes and cue settings which can be used to customise text.
///
@@ -424,12 +425,11 @@ impl Frame {
subtitles.get_cue_by_time(milliseconds).map(|(_, cue)| cue)
}
- /// Returns all the cues in order which timestamp is before or equal current frame.
+ /// Returns cues whose start is strictly before the current time plus `overlap`.
///
/// ### Params
/// * `overlap` – value in milliseconds is used to control when the next cue will join the stack,
- /// e.g if overlap is 1000ms, the next cue will join the stack when it's timestamp is 1000ms or less
- /// then the time of the current frame.
+ /// For example, 1000ms includes cues starting less than one second ahead.
pub fn get_cue_stack<'a, TSubtitles: FFramesSubtitles<'a>>(
&self,
subtitles: &'a TSubtitles,
diff --git a/fframes/src/lib.rs b/fframes/src/lib.rs
index fb71c2a7..938da675 100644
--- a/fframes/src/lib.rs
+++ b/fframes/src/lib.rs
@@ -81,6 +81,7 @@
//! - `cpu_renderer` (default): the tiny-skia based [`cpu::CpuRenderingBackend`] and the encoding
//! pipeline. Disable it for a `wasm32` build.
//! - `cli`: the [`cli`] module and its `clap` dependency.
+//! - `captions`: [`captions`], per-word SVG rendering over the media subtitles API.
//! - `compile-time-svgtree`: [`svgr!`] builds the SVG tree at compile time and hashes static
//! subtrees. Required by the Skia backend and by [`Shader`].
//! - `exif`: EXIF orientation of loaded images.
@@ -136,6 +137,8 @@ pub use renderer::*;
// Methods that we are not pub use ::* should be declared here:
pub mod animation;
+#[cfg(feature = "captions")]
+pub mod captions;
pub mod diagnostics;
pub mod error;
pub mod log;
diff --git a/fframes/src/media_provider.rs b/fframes/src/media_provider.rs
index 0216a440..a43e0e2b 100644
--- a/fframes/src/media_provider.rs
+++ b/fframes/src/media_provider.rs
@@ -20,7 +20,7 @@ impl Debug for RawFontData {
pub trait MediaProvider<'a>: Send + Sync + Debug {
fn resolve_audio(&'a self, name: &str) -> Option<&'a AudioData<'a>>;
fn resolve_image(&'a self, name: &str) -> Option<&'a media::ImageData<'a>>;
- fn resolve_subtitles(&'a self, name: &str) -> Option<&'a media::Subtitles<'a>>;
+ fn resolve_subtitles(&'a self, name: &str) -> Option<&'a media::Subtitles>;
fn resolve_video(&'a self, name: &str) -> Option<&'a media::VideoMedia>;
#[cfg(feature = "lottie")]
fn resolve_lottie(&'a self, _name: &str) -> Option<&'a crate::Lottie> {
@@ -60,6 +60,11 @@ pub trait MediaProvider<'a>: Send + Sync + Debug {
!self.get_all_video_data().is_empty()
}
+ /// All loaded subtitles, whether parsed from VTT or JSON.
+ fn get_all_subtitle_data(&self) -> Vec<(&media::Subtitles, &str)> {
+ Vec::new()
+ }
+
#[cfg(feature = "lottie")]
fn get_all_lottie_data(&self) -> Vec<(&crate::Lottie, &str)> {
Vec::new()
@@ -79,7 +84,7 @@ impl<'a> MediaProvider<'a> for () {
None
}
- fn resolve_subtitles(&'a self, _name: &str) -> Option<&'a media::Subtitles<'a>> {
+ fn resolve_subtitles(&'a self, _name: &str) -> Option<&'a media::Subtitles> {
None
}
@@ -115,7 +120,7 @@ impl StaticMediaProvider<'_> for () {
pub struct DynamicMediaProvider<'media> {
pub audio: HashMap<String, AudioData<'media>>,
pub images: HashMap<String, media::ImageData<'media>>,
- pub subtitles: HashMap<String, media::Subtitles<'media>>,
+ pub subtitles: HashMap<String, media::Subtitles>,
pub videos: HashMap<String, media::VideoMedia>,
pub fontdata: Vec<RawFontData>,
#[cfg(feature = "lottie")]
@@ -127,7 +132,7 @@ impl<'media> DynamicMediaProvider<'media> {
pub fn new(
audio: HashMap<String, AudioData<'media>>,
images: HashMap<String, media::ImageData<'media>>,
- subtitles: HashMap<String, media::Subtitles<'media>>,
+ subtitles: HashMap<String, media::Subtitles>,
videos: HashMap<String, media::VideoMedia>,
fonts_data: Vec<RawFontData>,
) -> Self {
@@ -158,11 +163,7 @@ impl<'media> DynamicMediaProvider<'media> {
/// Adds subtitles. `ctx.get_subtitles(name)` finds them by `name`.
#[must_use]
- pub fn with_subtitles(
- mut self,
- name: impl Into<String>,
- subtitles: media::Subtitles<'media>,
- ) -> Self {
+ pub fn with_subtitles(mut self, name: impl Into<String>, subtitles: media::Subtitles) -> Self {
self.subtitles.insert(name.into(), subtitles);
self
}
@@ -199,7 +200,7 @@ impl<'a> MediaProvider<'a> for DynamicMediaProvider<'a> {
self.images.get(name)
}
- fn resolve_subtitles(&'a self, name: &str) -> Option<&'a media::Subtitles<'a>> {
+ fn resolve_subtitles(&'a self, name: &str) -> Option<&'a media::Subtitles> {
self.subtitles.get(name)
}
@@ -259,6 +260,13 @@ impl<'a> MediaProvider<'a> for DynamicMediaProvider<'a> {
.map(|(name, data)| (data, name.as_str()))
.collect()
}
+
+ fn get_all_subtitle_data(&self) -> Vec<(&media::Subtitles, &str)> {
+ self.subtitles
+ .iter()
+ .map(|(name, data)| (data, name.as_str()))
+ .collect()
+ }
}
/// Combines several allocated media providers into one.
@@ -293,12 +301,21 @@ impl<'a, const N: usize> MediaProvider<'a> for CombinedMediaProvider<'a, N> {
.find_map(|provider| provider.resolve_image(name))
}
- fn resolve_subtitles(&self, name: &str) -> Option<&'a media::Subtitles<'_>> {
+ fn resolve_subtitles(&self, name: &str) -> Option<&'a media::Subtitles> {
self.0
.iter()
.find_map(|provider| provider.resolve_subtitles(name))
}
+ fn get_all_subtitle_data(&self) -> Vec<(&media::Subtitles, &str)> {
+ let mut names = std::collections::HashSet::new();
+ self.0
+ .iter()
+ .flat_map(|provider| provider.get_all_subtitle_data())
+ .filter(|(_, name)| names.insert(*name))
+ .collect()
+ }
+
fn resolve_video(&'a self, name: &str) -> Option<&'a media::VideoMedia> {
self.0
.iter()
diff --git a/fframes/src/renderer/media_directory.rs b/fframes/src/renderer/media_directory.rs
index dc01d71f..b99c2568 100644
--- a/fframes/src/renderer/media_directory.rs
+++ b/fframes/src/renderer/media_directory.rs
@@ -1,9 +1,10 @@
use super::renderer_error::FFramesRendererResult;
use crate::{
DynamicMediaProvider, RawFontData,
- media::{RawMediaFile, Subtitles, VideoMedia},
+ media::{CaptionError, RawMediaFile, Subtitles, VideoMedia},
};
use rayon::prelude::*;
+use serde::Serialize;
use std::{
collections::HashMap,
ffi::OsStr,
@@ -13,54 +14,147 @@ use std::{
sync::{Arc, Mutex},
};
-/// A struct representing owned media directory which can be used to process and fill
-/// the media provider. Basically represented as the vector of bytes where every media file is
-/// owned bytes vector.
-///
-/// Video trait implementation provides direct access to the bytes owned by this struct.
-pub struct MediaDirectory(Vec<(PathBuf, RawMediaFile)>);
+/// An owned snapshot of a media directory used to prepare a media provider.
+/// Subtitle JSON is parsed once during import and retained for preparation;
+/// other media keeps its bytes or source path as required by its decoder.
+pub struct MediaDirectory(Vec<(PathBuf, DirectoryMedia)>);
+
+enum DirectoryMedia {
+ Raw(RawMediaFile),
+ // Keep subtitle errors until preparation, matching the other media decoders.
+ // These become user errors with the file path, as with ordinary subtitle loading.
+ Subtitles(Result<Subtitles, String>),
+}
+
+/// What the directory importer accepted or skipped, before decoding.
+#[derive(Debug, Default, Serialize)]
+pub struct MediaImportReport {
+ pub accepted: Vec<PathBuf>,
+ pub skipped: Vec<SkippedMediaFile>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct SkippedMediaFile {
+ pub path: PathBuf,
+ pub reason: String,
+}
+
+#[derive(Debug, Clone, Copy)]
+pub struct MediaProcessingOptions {
+ /// Decode audio from video containers as well as standalone audio files.
+ pub decode_video_audio: bool,
+}
+
+impl Default for MediaProcessingOptions {
+ fn default() -> Self {
+ Self {
+ decode_video_audio: true,
+ }
+ }
+}
#[cfg(not(target_arch = "wasm32"))]
impl MediaDirectory {
pub fn read_folder(folder_path: impl AsRef<Path>) -> FFramesRendererResult<MediaDirectory> {
- let mut folder_content = vec![];
-
- if !folder_path.as_ref().is_dir() {
- return Err(io::Error::new(
- io::ErrorKind::InvalidInput, // todo change to NotADirectory when this https://github.com/rust-lang/rust/issues/86442 will be stable
- "resources_dir must be a folder",
- )
- .into());
+ let (directory, report) = Self::read_folder_with_report(folder_path)?;
+ for skipped in report.skipped {
+ eprintln!(
+ "fframes: skipped {}: {}",
+ skipped.path.display(),
+ skipped.reason
+ );
}
+ Ok(directory)
+ }
- for file in fs::read_dir(folder_path)? {
- let path = file?.path();
- if !path.is_file() {
- continue;
- }
-
- match path.extension().and_then(OsStr::to_str) {
- Some(
- "jpg" | "jpeg" | "png" | "gif" | "vtt" | "json" | "mp3" | "wav" | "flac"
- | "aac" | "pcm" | "ogg" | "mp2",
- ) => {
+ /// Import without printing, returning every accepted and skipped path. File names keep
+ /// their original case; only extension matching is case insensitive. I/O errors fail.
+ pub fn read_folder_with_report(
+ folder_path: impl AsRef<Path>,
+ ) -> FFramesRendererResult<(Self, MediaImportReport)> {
+ let mut files = fs::read_dir(folder_path)?
+ .map(|entry| entry.map(|entry| entry.path()))
+ .collect::<io::Result<Vec<_>>>()?;
+ files.sort();
+ // File reads and subtitle document parsing are independent. Keep them
+ // outside provider locks and preserve sorted report order on collection.
+ let files = files
+ .into_par_iter()
+ .map(|path| -> io::Result<_> {
+ let json = if path.is_file()
+ && path
+ .extension()
+ .and_then(OsStr::to_str)
+ .is_some_and(|extension| extension.eq_ignore_ascii_case("json"))
+ {
let bytes = fs::read(&path)?;
- folder_content.push((path, RawMediaFile::Data(bytes)));
+ Some(match parse_subtitle_json_document(&path, &bytes) {
+ Some(subtitles) => DirectoryMedia::Subtitles(subtitles),
+ None => DirectoryMedia::Raw(RawMediaFile::Data(bytes)),
+ })
+ } else {
+ None
+ };
+ Ok((path, json))
+ })
+ .collect::<io::Result<Vec<_>>>()?;
+ let mut folder_content = Vec::new();
+ let mut report = MediaImportReport::default();
+ for (path, json) in files {
+ let extension = path
+ .extension()
+ .and_then(OsStr::to_str)
+ .map(str::to_ascii_lowercase);
+ let reason = if path.is_file() {
+ match extension.as_deref() {
+ Some("json") if matches!(&json, Some(DirectoryMedia::Subtitles(_))) => None,
+ Some("json") if cfg!(feature = "lottie") => None,
+ Some("json") => Some(
+ "JSON is not recognized as subtitles; animations require the lottie feature",
+ ),
+ Some(
+ "jpg" | "jpeg" | "png" | "vtt" | "mp3" | "wav" | "flac" | "aac" | "pcm"
+ | "ogg" | "mp2" | "m4a" | "mp4" | "webm" | "mkv" | "avi" | "mov" | "flv"
+ | "wmv" | "m4v" | "ttf" | "ttc" | "otf" | "otc",
+ ) => None,
+ _ => Some("unsupported media extension"),
}
- Some(
- "mp4" | "webm" | "mkv" | "avi" | "mov" | "flv" | "wmv" | "m4v" | "ttf" | "ttc"
- | "otf" | "otc",
- ) => {
- folder_content.push((path.clone(), RawMediaFile::Stream(path)));
- }
- _ => {}
+ } else {
+ Some("not a file (directory import is not recursive)")
+ };
+ if let Some(reason) = reason {
+ report.skipped.push(SkippedMediaFile {
+ path,
+ reason: reason.to_owned(),
+ });
+ continue;
}
+ // Audio is decoded from its path below. Reading the compressed file into an
+ // unused byte vector first wastes both memory and I/O on every command.
+ let media = if let Some(json) = json {
+ json
+ } else {
+ DirectoryMedia::Raw(match extension.as_deref() {
+ Some("jpg" | "jpeg" | "png" | "vtt") => RawMediaFile::Data(fs::read(&path)?),
+ _ => RawMediaFile::Stream(path.clone()),
+ })
+ };
+ report.accepted.push(path.clone());
+ folder_content.push((path, media));
}
-
- Ok(MediaDirectory(folder_content))
+ Ok((MediaDirectory(folder_content), report))
}
pub fn process_media_source(&self) -> FFramesRendererResult<DynamicMediaProvider<'_>> {
+ self.process_media_source_with_options(MediaProcessingOptions::default())
+ }
+
+ /// Prepare media, optionally skipping audio embedded in video containers.
+ /// Explicit audio files are always decoded; subtitle metadata stays lazy.
+ pub fn process_media_source_with_options(
+ &self,
+ options: MediaProcessingOptions,
+ ) -> FFramesRendererResult<DynamicMediaProvider<'_>> {
let audio_hash = Mutex::new(HashMap::new());
let subtitles_hash = Mutex::new(HashMap::new());
let image_hash = Mutex::new(HashMap::new());
@@ -71,14 +165,32 @@ impl MediaDirectory {
self.0
.par_iter()
- .try_for_each(|(path, raw_file)| -> FFramesRendererResult<()> {
+ .try_for_each(|(path, media)| -> FFramesRendererResult<()> {
if let Some((extension, filename)) = path
.extension()
.and_then(OsStr::to_str)
.zip(path.file_name().and_then(OsStr::to_str))
{
- match (extension, raw_file) {
- ("mp3" | "wav" | "flac" | "aac" | "pcm" | "ogg" | "mp2", _) => {
+ let raw_file = match media {
+ DirectoryMedia::Subtitles(subtitles) => {
+ let subtitles = subtitles
+ .as_ref()
+ .map_err(|error| {
+ crate::error::FFramesError::UserError(format!(
+ "{}: {error}",
+ path.display()
+ ))
+ })?
+ .clone();
+ subtitles_hash
+ .lock()?
+ .insert(filename.to_owned(), subtitles);
+ return Ok(());
+ }
+ DirectoryMedia::Raw(raw_file) => raw_file,
+ };
+ match (extension.to_ascii_lowercase().as_str(), raw_file) {
+ ("mp3" | "wav" | "flac" | "aac" | "pcm" | "ogg" | "mp2" | "m4a", _) => {
let audio_data =
crate::media::PreloadedAudioData::decode_raw_file_stereo(
None, path,
@@ -90,13 +202,10 @@ impl MediaDirectory {
);
}
("vtt", RawMediaFile::Data(bytes)) => {
- let str_bytes = std::str::from_utf8(bytes)?;
-
- subtitles_hash.lock()?.insert(
- filename.to_owned(),
- Subtitles::parse(str_bytes)
- .map_err(crate::media::FFramesMediaError::from)?,
- );
+ let subtitles = parse_subtitles(path, bytes)?;
+ subtitles_hash
+ .lock()?
+ .insert(filename.to_owned(), subtitles);
}
#[cfg(feature = "lottie")]
("json", RawMediaFile::Data(bytes)) => {
@@ -128,8 +237,11 @@ impl MediaDirectory {
},
);
- if let Ok(audio_data) =
- crate::media::PreloadedAudioData::decode_raw_file_stereo(None, path)
+ if options.decode_video_audio
+ && let Ok(audio_data) =
+ crate::media::PreloadedAudioData::decode_raw_file_stereo(
+ None, path,
+ )
{
audio_hash.lock()?.insert(
filename.to_owned(),
@@ -155,3 +267,52 @@ impl MediaDirectory {
})
}
}
+
+fn parse_subtitle_json_document(path: &Path, bytes: &[u8]) -> Option<Result<Subtitles, String>> {
+ let named = path
+ .file_name()
+ .and_then(OsStr::to_str)
+ .is_some_and(|name| {
+ let lower = name.to_ascii_lowercase();
+ lower == "subtitles.json"
+ || lower == "captions.json"
+ || lower.ends_with(".subtitles.json")
+ || lower.ends_with(".captions.json")
+ });
+ let text = match std::str::from_utf8(bytes) {
+ Ok(text) => text,
+ Err(error) => return named.then(|| Err(error.to_string())),
+ };
+ // Explicit subtitle names have always used the content-detecting parser,
+ // including a WebVTT document saved with a .json suffix.
+ if named
+ && text
+ .trim_start()
+ .trim_start_matches('\u{feff}')
+ .trim_start()
+ .starts_with("WEBVTT")
+ {
+ return Some(Subtitles::parse(text).map_err(|error| error.to_string()));
+ }
+ match Subtitles::parse_json_document(text) {
+ Ok(Some(subtitles)) => Some(Ok(subtitles)),
+ Ok(None) => named.then(|| {
+ Err("expected a JSON object with a cues array for named subtitle media".into())
+ }),
+ Err(CaptionError::Json(error)) if error.is_syntax() || error.is_eof() => {
+ named.then(|| Err(CaptionError::Json(error).to_string()))
+ }
+ // Shape and timing errors mean a cues array was recognized. Keep these
+ // in the subtitle path instead of accidentally treating them as Lottie.
+ Err(error) => Some(Err(error.to_string())),
+ }
+}
+
+fn parse_subtitles(path: &Path, bytes: &[u8]) -> FFramesRendererResult<Subtitles> {
+ let text = std::str::from_utf8(bytes).map_err(|error| {
+ crate::error::FFramesError::UserError(format!("{}: {error}", path.display()))
+ })?;
+ Subtitles::parse(text).map_err(|error| {
+ crate::error::FFramesError::UserError(format!("{}: {error}", path.display())).into()
+ })
+}
diff --git a/fframes/src/text.rs b/fframes/src/text.rs
index 5ff0d09d..8f609cec 100644
--- a/fframes/src/text.rs
+++ b/fframes/src/text.rs
@@ -404,7 +404,7 @@ pub(crate) fn text_fit_impl<'a>(
pub(crate) fn text_get_width_impl<'a>(
font_query: FontQuery,
- text: &'a str,
+ text: &str,
font_source: &'a (dyn FontSource<'a> + 'a),
) -> Option<usize> {
let font_face = font_source.resolve_font(
diff --git a/fframes/src/video_data.rs b/fframes/src/video_data.rs
index b342ea17..721135ed 100644
--- a/fframes/src/video_data.rs
+++ b/fframes/src/video_data.rs
@@ -77,7 +77,8 @@ pub trait FFramesSyncedVideoFrame<'media> {
#[derive(Debug, Clone, Copy)]
pub struct SyncVideoFrameInput<'media> {
- /// The second of the video (or scene) when the file starts playing from its beginning.
+ /// Timeline delay in seconds, relative to the scene when called inside a scene.
+ /// Source playback starts at frame zero after this delay. Defaults to no delay.
/// It is not a position in the file: to play a part of a file use [`Clip`](crate::Clip).
pub start_from: f32,
/// If `true` the video playback will be looped and will start from the beginning on the end.
diff --git a/media-dir-macro/Cargo.toml b/media-dir-macro/Cargo.toml
index 90d64dfe..b55497db 100644
--- a/media-dir-macro/Cargo.toml
+++ b/media-dir-macro/Cargo.toml
@@ -32,7 +32,7 @@ fframes-media = { workspace = true, features = ["videotoolbox"] }
[features]
build-portable = ["fframes-media/build-portable"]
exif = ["fframes-media/kamadak-exif"]
-# `.json` files are Lottie animations (`fframes::Lottie`)
+# JSON without subtitle cues is treated as a Lottie animation (`fframes::Lottie`).
lottie = []
nightly = []
metadata = []
diff --git a/media-dir-macro/src/lib.rs b/media-dir-macro/src/lib.rs
index 79da983a..ebdde835 100644
--- a/media-dir-macro/src/lib.rs
+++ b/media-dir-macro/src/lib.rs
@@ -19,8 +19,10 @@ use syn::{Ident, parse_macro_input};
/// ```
///
/// Every file becomes a field of the struct. Fonts are embedded as they are; images,
-/// subtitles and audio are decoded at compile time. Audio is mixed down to mono unless the
+/// and audio are decoded at compile time. Subtitles are parsed once when preparing media.
+/// Audio is mixed down to mono unless the
/// `stereo` option is given; mono files stay mono either way.
+/// Subtitles can be `WebVTT` or JSON cues; both use the same owned subtitle type.
#[proc_macro]
pub fn include_media_dir(input: TokenStream) -> TokenStream {
let fframes_crate_ident = resolve_fframes_crate_ident();
@@ -86,6 +88,14 @@ pub fn include_media_dir(input: TokenStream) -> TokenStream {
}
}
});
+ let subtitle_identifiers = media_files
+ .iter()
+ .filter(|file| file.variant == MediaVariant::Subtitles)
+ .map(
+ |MediaFile {
+ ident, filename, ..
+ }| quote! { (&self.#ident, #filename) },
+ );
// These are the values we give to the renderer/editor to access all of the media dynamically.
let populate_fonts_expressions = media_files
@@ -218,7 +228,6 @@ pub fn include_media_dir(input: TokenStream) -> TokenStream {
}
}
- #[cfg(not(target_arch = "wasm32"))]
fn resolve_subtitles(&self, name: &str) -> Option<&#fframes_crate_ident::media::Subtitles> {
match name {
#(#subtitles_handle_tokens)*
@@ -226,15 +235,12 @@ pub fn include_media_dir(input: TokenStream) -> TokenStream {
}
}
- #[cfg(target_arch = "wasm32")]
- fn resolve_subtitles(&self, name: &str) -> Option<&#fframes_crate_ident::media::Subtitles> {
- fframes::log!("Warning: subtitles dynamic resolution in editor mode is not supported, please use the direct field of the autogenerated inline media struct.");
+ #resolve_lottie
- None
+ fn get_all_subtitle_data(&self) -> Vec<(&#fframes_crate_ident::media::Subtitles, &str)> {
+ vec![#(#subtitle_identifiers),*]
}
- #resolve_lottie
-
fn populate_font_source(&self, font_source: &mut dyn #fframes_crate_ident::FontSource) {
#(#populate_fonts_expressions);*
}
@@ -281,16 +287,17 @@ enum MediaVariant {
impl MediaVariant {
fn from_extension(file_name: &str, path: &Path) -> Option<Self> {
- match path.extension()?.to_str()? {
+ match path.extension()?.to_str()?.to_ascii_lowercase().as_str() {
// Decoded to samples at compile time (mono unless `stereo`), every format ffmpeg
// reads works.
"mp3" | "wav" | "flac" | "aac" | "ogg" | "m4a" => Some(MediaVariant::Audio),
"ttf" | "ttc" | "otf" | "otc" => Some(MediaVariant::Font),
"jpeg" | "png" | "jpg" => Some(MediaVariant::Image),
"vtt" => Some(MediaVariant::Subtitles),
+ "json" if is_subtitle_json(file_name, path) => Some(MediaVariant::Subtitles),
"json" if cfg!(feature = "lottie") => Some(MediaVariant::Lottie),
"json" => panic!(
- "{}: a `.json` file is a Lottie animation. Enable the `lottie` feature of fframes to embed it.",
+ "{}: JSON must contain subtitle cues, or enable the `lottie` feature of fframes to embed an animation.",
path.display()
),
_ if file_name.starts_with('.') => None,
@@ -302,6 +309,17 @@ impl MediaVariant {
}
}
+fn is_subtitle_json(file_name: &str, path: &Path) -> bool {
+ let lower = file_name.to_ascii_lowercase();
+ if matches!(lower.as_str(), "subtitles.json" | "captions.json")
+ || lower.ends_with(".subtitles.json")
+ || lower.ends_with(".captions.json")
+ {
+ return true;
+ }
+ std::fs::read_to_string(path).is_ok_and(|content| fframes_media::Subtitles::is_json(&content))
+}
+
#[derive(Debug)]
struct MediaFile {
path: PathBuf,
@@ -335,9 +353,7 @@ impl MediaFile {
let type_identifier = match self.variant {
MediaVariant::Audio => quote! { #fframes_crate_ident::AudioData<'static> },
MediaVariant::Image => quote! { #fframes_crate_ident::media::ImageData<'static> },
- // In wasm or dynamic media provider we load the Subtitles type, but in the static
- // compilation we expose direct Vtt struct that does not allocate.
- MediaVariant::Subtitles => quote! { #fframes_crate_ident::media::Vtt<'static> },
+ MediaVariant::Subtitles => quote! { #fframes_crate_ident::media::Subtitles },
MediaVariant::Lottie => quote! { #fframes_crate_ident::Lottie },
MediaVariant::Font => {
quote! { &'static [u8] }
@@ -398,13 +414,15 @@ impl MediaFile {
// the font file is basically and adhoc byte stream that is parsed on read at runtime
MediaVariant::Font => read_file_bytes_as_tokens(&self.path),
MediaVariant::Subtitles => {
+ // Embed the complete document so application metadata survives the
+ // same parser used by runtime loading, without a second cue schema.
let file_str = std::fs::read_to_string(&self.path).unwrap();
let file_str_literal = Literal::string(&file_str);
quote! {
- #fframes_crate_ident::media::Vtt::parse(
+ #fframes_crate_ident::media::Subtitles::parse(
#file_str_literal
- ).map_err(#fframes_crate_ident::media::FFramesMediaError::VttError)?
+ ).map_err(#fframes_crate_ident::media::FFramesMediaError::from)?
}
}
// `prepare()` parses the file. An invalid file makes `prepare()` fail.
@@ -520,9 +538,12 @@ fn create_image_identifier_for_platform_wasm(
) -> impl ToTokens {
use base64::Engine;
let encoded: String = base64::engine::general_purpose::STANDARD_NO_PAD.encode(file_bytes);
- let extension = file_name.split('.').next_back();
+ let extension = file_name
+ .split('.')
+ .next_back()
+ .map(str::to_ascii_lowercase);
- let mime_type = match extension {
+ let mime_type = match extension.as_deref() {
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
_ => panic!("File {file_name} is not a valid image file"),
diff --git a/scripts/e2e.mjs b/scripts/e2e.mjs
index 710accec..937410a0 100644
--- a/scripts/e2e.mjs
+++ b/scripts/e2e.mjs
@@ -1,7 +1,7 @@
// Renders key frames of every example through its command line with one renderer and compares
// them with odiff to e2e/snapshots, which every renderer has to match. Frames and diffs of the
// run go to target/e2e/<renderer>.
-// node scripts/e2e.mjs cpu|skia-cpu|gpu [--update]
+// node scripts/e2e.mjs cpu|skia-cpu|gpu [--update] [--example name]
import { spawnSync } from "node:child_process";
import {
copyFileSync,
@@ -14,11 +14,21 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { compare } from "odiff-bin";
-const [renderer, flag] = process.argv.slice(2);
-const update = flag === "--update";
-if (!["cpu", "skia-cpu", "gpu"].includes(renderer) || (flag && !update)) {
- console.error("usage: node scripts/e2e.mjs cpu|skia-cpu|gpu [--update]");
+const [renderer, ...flags] = process.argv.slice(2);
+let update = false;
+let selectedExample;
+const usage = () => {
+ console.error(
+ "usage: node scripts/e2e.mjs cpu|skia-cpu|gpu [--update] [--example name]"
+ );
process.exit(1);
+};
+if (!["cpu", "skia-cpu", "gpu"].includes(renderer)) usage();
+for (let i = 0; i < flags.length; i++) {
+ if (flags[i] === "--update") update = true;
+ else if (flags[i] === "--example" && flags[i + 1] && !selectedExample)
+ selectedExample = flags[++i];
+ else usage();
}
// Renderers resample images and round colours differently: odiff's colour threshold 0.15
@@ -34,10 +44,12 @@ const out = join(target, "e2e", renderer);
// `skia`: shaders, which the CPU renderer (tiny-skia) does not run. shader-mode is not here: its
// media is kept outside Git.
// prettier-ignore
-const examples = [
+const allExamples = [
{ dir: "anamorphic-video", pkg: "anamorphic-video", bin: "anamorphic-video", frames: "50%" },
{ dir: "audio-announce", pkg: "audio-announce-example", bin: "audio_announce_example_bin", frames: "5s,30s" },
{ dir: "beta", pkg: "beta-example", bin: "beta_example_bin", frames: "CodeDemoScene@50%,IphoneScene@50%,BetaExamples@50%" },
+ // Preset layouts, typed highlights, wrapping and simultaneous cues.
+ { dir: "captions", pkg: "captions-example", bin: "captions-example", frames: "1.5s,5.2s,7s" },
{ dir: "conference-splash-screen", pkg: "conference-splash-screen-example", bin: "conference_splash_screen_bin", frames: "SponsorScene@50%,SpeakerScene@50%" },
{ dir: "fframes-intro", pkg: "fframes-intro", bin: "fframes-intro", frames: "CodeScene@50%,[email protected],[email protected],OutroScene@7s", skia: true },
{ dir: "hello-world", pkg: "hello-world-example", bin: "hello_world_example_bin", frames: "5s,20s" },
@@ -55,6 +67,18 @@ const examples = [
{ dir: "tiktok", pkg: "tiktok-example", bin: "tiktok_example_bin", frames: "10s,30s" },
];
+const examples = allExamples.filter(
+ ({ dir }) => !selectedExample || dir === selectedExample
+);
+if (!examples.length) {
+ console.error(`unknown example: ${selectedExample}`);
+ process.exit(1);
+}
+if (selectedExample && renderer === "cpu" && examples[0].skia) {
+ console.error(`${selectedExample} requires skia-cpu or gpu`);
+ process.exit(1);
+}
+
const run = (command, args, cwd) =>
spawnSync(command, args, { cwd, stdio: ["ignore", "ignore", "inherit"] })
.status === 0;
@@ -65,7 +89,10 @@ const build = ["build", "--release", "--bins", ...packages];
if (spawnSync("cargo", build, { cwd: root, stdio: "inherit" }).status !== 0)
process.exit(1);
-rmSync(out, { recursive: true, force: true });
+rmSync(selectedExample ? join(out, selectedExample) : out, {
+ recursive: true,
+ force: true,
+});
const failed = [];
const created = [];
for (const { dir, bin, frames, skia, args = [] } of examples) {
diff --git a/skills/fframes-video/SKILL.md b/skills/fframes-video/SKILL.md
index beedc25a..985147ad 100644
--- a/skills/fframes-video/SKILL.md
+++ b/skills/fframes-video/SKILL.md
@@ -71,9 +71,11 @@ product with only the text changed. If it would, change the idea, not the colors
### The video is the Rust crate and `media/`
-Every decision about the video is in Rust code: which part of a file plays, when and at what
-speed, how a voice syncs with its picture, captions, music, grading and the export settings.
-Put the files into `media/` as the user gave them.
+The Rust crate and its media data define which part of a file plays, when and at what speed,
+how a voice syncs with its picture, captions, music, grading and the export settings.
+Keep reusable drawing behavior in Rust; timed caption text and per-word enum metadata can
+live in VTT/JSON loaded through the same media provider. Put source files into `media/`
+as the user gave them.
- Do not write Python, shell or ffmpeg scripts that cut, join, retime or grade media, that
generate Rust code or data tables, or that change the file after `$R render` (remux, retag,
@@ -308,6 +310,9 @@ impl Video for MyVideo<'_> {
- Measure text rather than guess: `frame.text_width`, `frame.text_fit(.., TextOverflow::Ellipsis)`,
`frame.text_break_lines` for paragraphs. `inspect` catches text leaving the canvas, not text
leaving its own box, so check boxes in a `frame` PNG.
+- For subtitles or timed lyrics, read `references/captions.md`: a VTT or JSON track in
+ `media/`, one `Captions` component kept on the video, `metadata.typed::<T>()` for
+ per-word effects. Never parse JSON or rebuild tracks per frame.
- Camera or phone footage plays through `fframes::Clip` inside scenes (see the rules at the
top). `frame.video_frame_at(ctx, file, seconds, None)` is one frame of a file (a freeze frame).
- GPU shaders (SkSL or Shadertoy GLSL) run on the Skia backend through `fframes::Shader`; they
diff --git a/skills/fframes-video/references/api.md b/skills/fframes-video/references/api.md
index 508f42e3..4fe35352 100644
--- a/skills/fframes-video/references/api.md
+++ b/skills/fframes-video/references/api.md
@@ -1,5 +1,9 @@
# fframes API cheat sheet
+For VTT/JSON subtitles, typed word metadata, reusable highlights and caching, see
+[captions.md](captions.md). The `captions` feature adds SVG rendering; subtitle parsing
+and media loading remain available without it.
+
Examples in the fframes repository worth reading: [beta](https://github.com/dmtrKovalenko/fframes/tree/main/examples/beta) (scenes, images), [audio-announce](https://github.com/dmtrKovalenko/fframes/tree/main/examples/audio-announce)
(audio visualisation, video sources), [teej-podcast](https://github.com/dmtrKovalenko/fframes/tree/main/examples/teej-podcast) (Skia backend, stereo
media loaded at runtime), [shaders](https://github.com/dmtrKovalenko/fframes/tree/main/examples/shaders) and [neon-triangle](https://github.com/dmtrKovalenko/fframes/tree/main/examples/neon-triangle) (GPU
diff --git a/skills/fframes-video/references/captions.md b/skills/fframes-video/references/captions.md
new file mode 100644
index 00000000..fdf30895
--- /dev/null
+++ b/skills/fframes-video/references/captions.md
@@ -0,0 +1,177 @@
+# Subtitles and captions
+
+Use this for subtitles, lyrics and any typography driven by speech. Other videos do not
+need a caption track.
+
+## The data
+
+A caption track is a WebVTT file or a JSON file in `media/`. `CaptionTrack::parse` detects
+the format from the content; both become the same owned `CaptionTrack` (`Subtitles` is an
+alias). Use VTT when you only have phrases. Use JSON when you have word timings or want
+per-word settings:
+
+```json
+{
+ "cues": [
+ {
+ "start": 0, "end": 2,
+ "words": [
+ {"text": "Choose", "start": 0, "end": 0.7},
+ {"text": "the", "start": 0.7, "end": 0.9},
+ {"text": "Moon", "start": 0.9, "end": 1.5,
+ "metadata": {"effect": "underline", "color": "#ffd166"}},
+ {"text": ".", "start": 1.5, "end": 1.6, "space_before": false}
+ ]
+ },
+ {"start": 2.4, "end": 4, "text": "A phrase without word timing.", "speaker": "B"}
+ ]
+}
+```
+
+- Times are seconds on one clock; a cue or word is visible over `[start, end)`.
+- Word times are absolute, not relative to the cue. Words are ordered, do not overlap and
+ lie inside their cue; the cue may start earlier or end later to hold the phrase on screen.
+- A cue has either `text` or `words`. Cues are ordered by start and may overlap (two
+ speakers). Optional `id`, `speaker` and `metadata` on cues, `id`, `space_before` and
+ `metadata` on words. `metadata` is any JSON object; the parser keeps it untouched.
+- Do not fabricate word timings by splitting a phrase evenly. Use timings from a
+ transcription that outputs word timestamps, or show the whole phrase.
+- Invalid timing, ordering or duplicate ids fail at load with the path of the field
+ (`cues[3].words[1].end`), not at render time.
+
+Loading is the same as for any other media: `include_media_dir!` embeds the file,
+`MediaDirectory::read_folder` reads it at runtime, the editor loads it over HTTP. JSON
+whose top-level object has `cues` is a caption track; any other JSON is not.
+`ctx.get_subtitles("speech.json")` returns the `&CaptionTrack`: `cues()`,
+`active_cues(seconds)`, and on each `CaptionCue` `phrase()`, `words`, `metadata`.
+A track can also be built in code: `CaptionTrack::new([CaptionCue::words(0.0, 2.0,
+[CaptionWord::new("Choose", 0.0, 0.7), ..]), CaptionCue::text(2.4, 4.0, "..")])`.
+
+For a plain phrase caption `frame.get_subtitle_phrase(track)` returns the current cue
+text; this older helper includes the cue's end timestamp, `Captions` and `active_cues`
+do not. Instantaneous VTT cues remain available to the legacy lookup at their exact
+timestamp; JSON cues require a positive duration. Legacy `get_cue_stack` includes cue
+starts strictly before `time + overlap`.
+
+## Rendering: `Captions` (feature `captions`)
+
+`fframes::captions::Captions` lays out a track once and draws the visible words of any
+frame. Build it in the video constructor and keep it on the video:
+
+```rust
+use fframes::captions::{CaptionClock, CaptionMode, CaptionRect, Captions};
+
+let captions = Captions::from_media("speech.json", CaptionRect::new(120.0, 760.0, 1680.0, 240.0))
+ .font("DM Sans", 64) // family and size, measured from the loaded font
+ .font_weight(600)
+ .line_height(1.25)
+ .mode(CaptionMode::Highlight)
+ .active_fill("#ffd166").upcoming_fill("#aeb4c0").spoken_fill("#ffffff")
+ .outline("#000000", 3.0) // stroke behind the glyphs
+ .active_background("#1b1f2a", 10.0) // rounded box behind the active word, padding
+ .underline("#ffd166", 5.0); // bar under the active word
+```
+
+`Captions::new(track, rect)` takes an owned `CaptionTrack` instead of a media name.
+The rectangle is in composition pixels. Each phrase is wrapped to its width, lines are
+centred, and the block is anchored to the bottom edge of the rectangle; simultaneous cues
+are stacked in order. Nothing moves when the active word changes.
+
+In `render_frame` insert `{self.captions.render(&mut frame, ctx)}`. `render` resolves the
+track from the media provider, lays it out on first use (and again if the provider gets a
+new track under that name), and returns the SVG for the frame. Missing font, a word wider
+than the rectangle, or more lines than fit are reported as `inspect` errors and the captions
+are left out of that frame; `try_render` returns them as `CaptionError` instead.
+
+Modes:
+
+- `Highlight` (default): the whole phrase, each word coloured by state
+ (`upcoming_fill`, `active_fill`, `spoken_fill`).
+- `Karaoke`: like Highlight, the active word fills left to right with its progress.
+- `Reveal`: words appear as they are spoken and stay; upcoming words are hidden.
+- `Word`: only the active word, centred in the rectangle; nothing during gaps.
+
+A VTT phrase has no word timing: every mode shows the whole phrase in `spoken_fill`.
+
+Clock: by default the caption time is the scene-local frame time, like animations. Use
+`.clock(CaptionClock::Global)` for a transcript of the whole video inside scenes, or
+`render_at(seconds, &mut frame, ctx)` when you map the time yourself (a clip that starts
+later, plays faster, or is cut).
+
+## Custom word drawing
+
+`highlight_with` runs a callback for every active timed word, `render_with` for every
+visible word. The callback gets a borrowed `CaptionWordScope` and the owned preset SVG of
+that word, and returns the SVG to draw. Coordinates are local to the word: `(0, 0)` is the
+top-left of its advance box, `scope.width()` × `scope.height()`. The component translates
+the result into place, nothing is clipped, so decorations may extend outside the box.
+
+```rust
+#[derive(serde::Deserialize)]
+#[serde(tag = "effect", rename_all = "kebab-case")]
+enum Highlight {
+ Underline { color: String },
+ Fill { color: String },
+}
+
+let captions = self.captions.highlight_with(&mut frame, ctx, |scope, text| {
+ match scope.word.metadata.typed::<Highlight>() {
+ Some(Highlight::Underline { color }) => fframes::svgr!(
+ <g>{text}
+ <rect x="0" y={scope.height() - 4.0} width={scope.width()} height="4"
+ fill={color.as_str()} /></g>
+ ),
+ Some(Highlight::Fill { color }) => scope.mask_text(fframes::svgr!(
+ <rect width={scope.width()} height={scope.height()} fill={color.as_str()} />
+ )),
+ None => text, // keep the preset drawing
+ }
+});
+```
+
+What the scope offers:
+
+- `scope.word`: `text`, `state` (`Upcoming | Active | Spoken`), `progress` (0..=1 of the
+ word's duration), `start`/`end` (`None` for a VTT phrase), `metadata`, `cue_index`,
+ `word_index`. `scope.cue_metadata` is the cue's object. `scope.is_active()`.
+- `scope.time` (caption seconds), `scope.elapsed()` (seconds since the word started),
+ `scope.frame` (the `Frame`, for `frame.animate` or `Shader::draw`).
+- `scope.composition_rect`: where the word lands on the canvas, if something else must
+ align with it.
+- `scope.mask_text(svg)`: show `svg` only through the word's glyphs (gradient or shader
+ fills). `scope.clip(svg)`: clip to the advance box. `scope.id("key")`: an SVG id that is
+ unique per word and frame, for `<defs>` the callback creates.
+- `render_at_with` and `highlight_at_with` take explicit seconds; every variant has a
+ `try_` form that returns the error.
+
+For a layout of your own, `captions.words_at(seconds, &mut frame, ctx)` returns the
+positioned words (`rect` in composition pixels, state, progress, metadata) and you draw
+them yourself.
+
+## Metadata
+
+Describe per-word or per-cue settings as a Serde type, preferably an enum with one variant
+per effect and the parameters inside the variant. Defaults live in Rust; JSON carries only
+the choices. `metadata.typed::<T>()` decodes the object as `T` the first time it is asked
+for and caches the result (also a failed decode) for that object, shared by every frame,
+thread and clone of the track. Nothing is registered up front and no JSON is parsed per
+frame. It returns `None` when the object is empty or does not match `T`; if a setting is
+required, check it in the constructor and report the cue and word. `metadata.get("key")`
+reads the raw JSON value.
+
+## Rules that keep it fast
+
+- Load the track once through the media provider; never call `CaptionTrack::parse`,
+ `serde_json` or `metadata.parse::<T>()` (the uncached decode) in `render_frame`.
+- One `Captions` per treatment, built once. Changing font or layout settings means
+ building a new one. Layout and font measurements are cached inside it.
+- Build `Shader`s and any glyph textures once; change only uniforms per frame.
+- Drawing costs about a microsecond per visible word; the size of the track does not matter.
+
+## Check it
+
+`$R inspect` reports caption layout errors (font not loaded, word wider than the box, too
+many lines, stacked cues taller than the box). Then look: `$R frame 1.4s,2.3s` at word
+boundaries, a gap between cues, and a frame where two cues overlap, and `$R strip <cue
+range> -n 8` to see the highlight move. Check that the lowest line clears the safe area
+and that the active colour reads against the real background.
diff --git a/webvtt-parser/src/lib.rs b/webvtt-parser/src/lib.rs
index 8783876c..9494f990 100644
--- a/webvtt-parser/src/lib.rs
+++ b/webvtt-parser/src/lib.rs
@@ -234,10 +234,10 @@ impl Display for VttCue<'_> {
"{}{}{} --> {}{}\n{}\n",
self.note
.as_ref()
- .map_or_else(String::new, |comment| format!("NOTE {comment}\n")),
+ .map_or_else(String::new, |comment| format!("NOTE {comment}\n\n")),
self.name
.as_ref()
- .map_or_else(String::new, |comment| format!("NOTE {comment}\n")),
+ .map_or_else(String::new, |name| format!("{name}\n")),
self.start,
self.end,
self.cue_settings
@@ -591,18 +591,63 @@ mod tests {
}
#[test]
- fn incomplete_file() {
- let content = fs::read_to_string("tests/incomplete.vtt").unwrap();
-
- match Vtt::parse(&content) {
- Ok(_) => panic!("The data is incomplete, should fail."),
- Err(error) => {
- assert_eq!(error.looking_for, "Digit");
- assert_eq!(&error.fragment, Span::from("").fragment());
- }
+ fn empty_document() {
+ let content = include_str!("../tests/empty.vtt");
+ assert_eq!(Vtt::parse(content).unwrap().cues, []);
+ for header in [
+ "WEBVTT",
+ "WEBVTT\n",
+ "WEBVTT header comment",
+ "WEBVTT\nKind: captions",
+ "WEBVTT\nKind: captions\n",
+ "WEBVTT\n\nNOTE trailing comment",
+ "WEBVTT\n\nNOTE",
+ ] {
+ assert!(Vtt::parse(header).unwrap().cues.is_empty(), "{header}");
+ }
+ }
+
+ #[test]
+ fn timing_line_terminates_header_without_blank_separator() {
+ for ending in ["\n", "\r\n"] {
+ let input =
+ "WEBVTT\nKind: captions\n00:00.000 --> 00:01.000\nHello\n".replace('\n', ending);
+ let parsed = Vtt::parse(&input).unwrap();
+ assert_eq!(parsed.slugs.get("Kind"), Some(&"captions"));
+ assert_eq!(parsed.cues.len(), 1);
+ assert_eq!(parsed.cues[0].text, "Hello");
}
}
+ #[test]
+ fn note_blocks_and_identifiers_round_trip() {
+ for ending in ["\n", "\r\n"] {
+ let content = concat!(
+ "WEBVTT\n\nNOTE\nfirst comment\n\nNOTE\tsecond\ncontinued\n\n",
+ "NOTEworthy identifier\n00:01.000 --> 00:02.000\nHello\n\n",
+ "NOTE\n\n00:02.000 --> 00:03.000\nWorld\n\n",
+ "NOTE identifier\n00:03.000 --> 00:04.000\nKeep this cue\n\n",
+ "NOTE trailing\ncomment"
+ )
+ .replace('\n', ending);
+ let parsed = Vtt::parse(&content).unwrap();
+ assert_eq!(parsed.cues.len(), 3);
+ assert_eq!(parsed.cues[0].name, Some("NOTEworthy identifier"));
+ let note = format!("second{ending}continued");
+ assert_eq!(parsed.cues[0].note, Some(note.as_str()));
+ assert_eq!(parsed.cues[1].note, Some(""));
+ assert_eq!(parsed.cues[2].name, Some("NOTE identifier"));
+ assert_eq!(parsed.cues[2].note, None);
+ assert_eq!(parsed.cues[2].text, "Keep this cue");
+ let exported = parsed.to_string();
+ assert_eq!(Vtt::parse(&exported).unwrap(), parsed);
+ }
+ assert!(
+ Vtt::parse("WEBVTT\n\nNOTE comment\ninvalid --> comment\n\n").is_err(),
+ "malformed timing-bearing blocks must not silently discard text"
+ );
+ }
+
#[test]
fn invalid_file() {
match Vtt::parse(include_str!("../tests/invalid.vtt")) {
diff --git a/webvtt-parser/src/vtt_parser.rs b/webvtt-parser/src/vtt_parser.rs
index 460b8591..6848567f 100644
--- a/webvtt-parser/src/vtt_parser.rs
+++ b/webvtt-parser/src/vtt_parser.rs
@@ -1,31 +1,29 @@
use crate::Span;
use nom::branch::alt;
-use nom::character::complete::{digit1, newline, space0};
-use nom::error::{Error, context};
-use nom::{
- IResult,
- bytes::complete::{is_not, tag, take, take_until},
- combinator::opt,
- multi::{many0, many1},
- sequence::{preceded, separated_pair},
-};
+use nom::character::complete::{digit1, line_ending, not_line_ending};
+use nom::error::{Error, ErrorKind, context};
+use nom::{IResult, Slice, bytes::complete::tag, combinator::opt, multi::many0};
use crate::cue_settings_parser::parse_cue_settings;
use crate::{START_MARKER, Time, Vtt, VttCue};
fn parse_note(input: Span<'_>) -> IResult<Span<'_>, Option<&str>> {
- let (rest, line) = take_until("\n")(input)?;
-
- if !line.contains("NOTE ") {
- // if NOTE not found return same input
+ let (_, line) = not_line_ending(input)?;
+ let Some(suffix) = line.fragment().strip_prefix("NOTE") else {
+ return Ok((input, None));
+ };
+ if !suffix.is_empty() && !suffix.starts_with([' ', '\t']) {
return Ok((input, None));
}
-
- // note body is the whole line before \n that we get on :29 without "NOTE "
- let (note_body, _) = tag("NOTE ")(line)?;
- let (rest, _) = newline(rest)?;
-
- Ok((rest, Some(&note_body)))
+ // NOTE is a complete block, not a single line attached to a timing line.
+ let (rest, block) = parse_payload(input)?;
+ // A timing line makes this a cue whose identifier starts with NOTE. Let the
+ // cue parser validate it rather than silently swallowing potentially visible text.
+ if block.contains("-->") {
+ return Ok((input, None));
+ }
+ let note = block.fragment()[4..].trim();
+ Ok((rest, Some(note)))
}
pub(crate) fn parse_number<TNumber: std::str::FromStr>(input: Span) -> IResult<Span, TNumber> {
@@ -43,60 +41,74 @@ pub(crate) fn parse_number<TNumber: std::str::FromStr>(input: Span) -> IResult<S
}
fn parse_time_without_hours(input: Span) -> IResult<Span, Time> {
- let (input, minute) = parse_number::<u64>(input)?;
+ let (input, minute) = parse_time_component(input, 2, 59)?;
let (input, _) = tag(":")(input)?;
- let (input, second) = parse_number::<u64>(input)?;
+ let (input, second) = parse_time_component(input, 2, 59)?;
let (input, _) = tag(".")(input)?;
- let (input, millisecond) = parse_number::<u64>(input)?;
+ let (input, millisecond) = parse_time_component(input, 3, 999)?;
Ok((input, Time(minute * 60000 + second * 1000 + millisecond)))
}
fn parse_time_with_hours(input: Span) -> IResult<Span, Time> {
- let (input, hour) = parse_number::<u64>(input)?;
+ let original = input;
+ let (input, hours) = digit1(input)?;
+ let hour = hours.parse::<u64>().ok().filter(|_| hours.len() >= 2);
+ let Some(hour) = hour else {
+ return Err(nom::Err::Failure(Error::new(original, ErrorKind::Verify)));
+ };
let (input, _) = tag(":")(input)?;
- let (input, minute) = parse_number::<u64>(input)?;
+ let (input, minute) = parse_time_component(input, 2, 59)?;
let (input, _) = tag(":")(input)?;
- let (input, second) = parse_number::<u64>(input)?;
+ let (input, second) = parse_time_component(input, 2, 59)?;
let (input, _) = tag(".")(input)?;
- let (input, millisecond) = parse_number::<u64>(input)?;
+ let (input, millisecond) = parse_time_component(input, 3, 999)?;
- Ok((
- input,
- Time(hour * 3_600_000 * minute * 60000 + second * 1000 + millisecond),
- ))
+ let milliseconds = hour
+ .checked_mul(3_600_000)
+ .and_then(|hours| hours.checked_add(minute * 60000 + second * 1000 + millisecond))
+ .ok_or_else(|| nom::Err::Failure(Error::new(original, ErrorKind::Verify)))?;
+ Ok((input, Time(milliseconds)))
+}
+
+fn parse_time_component(input: Span, digits: usize, maximum: u64) -> IResult<Span, u64> {
+ let original = input;
+ let (input, number) = digit1(input)?;
+ let value = number.parse::<u64>().ok();
+ match value {
+ Some(value) if number.len() == digits && value <= maximum => Ok((input, value)),
+ _ => Err(nom::Err::Error(Error::new(original, ErrorKind::Verify))),
+ }
}
fn parse_cue_identifier(input: Span<'_>) -> IResult<Span<'_>, Option<&str>> {
- let (rest, line) = take_until("\n")(input)?;
+ let (rest, line) = not_line_ending(input)?;
- if line.contains("-->") {
+ if line.contains("-->") || line.is_empty() {
// if this is not an identifier return same input
Ok((input, None))
} else {
- let (rest, _) = newline(rest)?;
+ let (rest, _) = line_ending(rest)?;
Ok((rest, Some(&line)))
}
}
fn parse_cue(input: Span) -> IResult<Span, VttCue> {
- let (input, _) = opt(newline)(input)?;
- let (input, _) = opt(newline)(input)?;
+ let (input, _) = many0(line_ending)(input)?;
let mut parse_time = alt((parse_time_without_hours, parse_time_with_hours));
- let (input, note) = parse_note(input)?;
let (input, name) = parse_cue_identifier(input)?;
let (input, start) = parse_time(input)?;
let (input, _) = tag(" --> ")(input)?;
let (input, end) = parse_time(input)?;
+ if end.as_milliseconds() < start.as_milliseconds() {
+ return Err(nom::Err::Failure(Error::new(input, ErrorKind::Verify)));
+ }
let (input, cue_settings) = opt(parse_cue_settings)(input)?;
- let (input, _) = opt(newline)(input)?;
+ let (input, _) = opt(line_ending)(input)?;
- let (input, text) = match take_until::<_, _, Error<_>>("\n")(input) {
- Ok(val) => val,
- Err(_) => take(input.len())(input)?,
- };
+ let (input, text) = parse_payload(input)?;
Ok((
input,
@@ -108,27 +120,78 @@ fn parse_cue(input: Span) -> IResult<Span, VttCue> {
Some(settings) if settings.is_empty() => None,
other => other,
},
- note,
+ note: None,
text: &text,
},
))
}
+/// Borrow the entire payload, preserving internal line endings and markup. Only the line
+/// ending immediately before a blank separator (or EOF) is excluded from the cue text.
+fn parse_payload(input: Span<'_>) -> IResult<Span<'_>, Span<'_>> {
+ let mut remaining = input;
+ loop {
+ let (after_line, line) = not_line_ending(remaining)?;
+ let length = after_line.location_offset() - input.location_offset();
+ if after_line.is_empty() || line.is_empty() {
+ return Ok((input.slice(length..), input.slice(..length)));
+ }
+ let (after_ending, _) = line_ending(after_line)?;
+ if after_ending.is_empty()
+ || after_ending.starts_with('\n')
+ || after_ending.starts_with("\r\n")
+ {
+ return Ok((input.slice(length..), input.slice(..length)));
+ }
+ remaining = after_ending;
+ }
+}
+
pub fn parse(text: Span) -> IResult<Span, Vtt> {
let (text, _) = context("WebVTT file must start with WEBVTT", tag(START_MARKER))(text)?;
- let (subtitles_part, slug_part) = take_until("\n\n")(text)?;
-
- let (text, slugs) = many0(separated_pair(
- preceded(newline, take_until(":")),
- tag(":"),
- preceded(space0, is_not("\n")),
- ))(slug_part)?;
-
- let (rest, cues) = many1(parse_cue)(subtitles_part)?;
- let (rest, _) = many0(newline)(rest)?;
+ let (text, header_comment) = not_line_ending(text)?;
+ if !header_comment.is_empty()
+ && !header_comment.starts_with(' ')
+ && !header_comment.starts_with('\t')
+ {
+ return Err(nom::Err::Failure(Error::new(text, ErrorKind::Tag)));
+ }
+ let (mut text, _) = opt(line_ending)(text)?;
+ let mut slugs = std::collections::HashMap::new();
+ while !text.is_empty() {
+ let (rest, line) = not_line_ending(text)?;
+ // A timing line ends the header even without a blank separator.
+ if line.contains("-->") {
+ break;
+ }
+ let (rest, _) = opt(line_ending)(rest)?;
+ text = rest;
+ if line.is_empty() {
+ break;
+ }
+ if let Some((key, value)) = line.fragment().split_once(':') {
+ slugs.insert(key, value.trim_start());
+ }
+ }
- if !rest.is_empty() {
- let _ = parse_cue(rest)?;
+ let mut cues = Vec::new();
+ let mut note = None;
+ loop {
+ let (rest, _) = many0(line_ending)(text)?;
+ text = rest;
+ if text.is_empty() {
+ break;
+ }
+ let (rest, next_note) = parse_note(text)?;
+ if next_note.is_some() {
+ note = next_note;
+ text = rest;
+ continue;
+ }
+ let (rest, mut cue) = parse_cue(text)?;
+ cue.note = note.take();
+ cues.push(cue);
+ text = rest;
}
Ok((
@@ -136,10 +199,7 @@ pub fn parse(text: Span) -> IResult<Span, Vtt> {
Vtt {
cues,
style: None,
- slugs: slugs
- .into_iter()
- .map(|(key, val)| (*key, *val))
- .collect::<std::collections::HashMap<_, _>>(),
+ slugs,
},
))
}
diff --git a/webvtt-parser/tests/complex-vtt-example.vtt b/webvtt-parser/tests/complex-vtt-example.vtt
index 208a1068..1756eb5e 100644
--- a/webvtt-parser/tests/complex-vtt-example.vtt
+++ b/webvtt-parser/tests/complex-vtt-example.vtt
@@ -24,6 +24,7 @@ Language: en
<v Roger Bingham>at the AMNH.
NOTE this is comment
+
00:24.000 --> 00:26.000
<v Roger Bingham>Thank you for walking down here.
diff --git a/webvtt-parser/tests/incomplete.vtt b/webvtt-parser/tests/empty.vtt
similarity index 100%
rename from webvtt-parser/tests/incomplete.vtt
rename to webvtt-parser/tests/empty.vtt