programmatic video rendering framework that is actually fast
feat: add shader-mode GPU promo and authoring guidance (#191)
Dmitriy Kovalenko76a94a6b3cc5
diff --git a/Cargo.lock b/Cargo.lockindex 2c791002..7dfe8c54 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3317,6 +3317,15 @@ dependencies = ["serde_core",]+[[package]]+name = "shader-mode"+version = "1.2.0"+dependencies = [+ "fframes",+ "fframes_native_player",+ "fframes_skia_renderer",+]+[[package]]name = "shaders-bridge-example"version = "1.2.0"diff --git a/Cargo.toml b/Cargo.tomlindex 89ac55d2..05783c2e 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -49,6 +49,7 @@ members = ["examples/signal-lab","examples/fframes-intro","examples/made-of-motion",+ "examples/shader-mode",][workspace.lints.rust]diff --git a/README.md b/README.mdindex 059639fc..20fbd56f 100644--- a/README.md+++ b/README.md@@ -172,6 +172,7 @@ The full API reference is on [docs.rs/fframes](https://docs.rs/fframes).| [signal-lab](examples/signal-lab) | a 24 second motion study: product UI, data storytelling and a technical explainer || [motion-graphics](examples/motion-graphics) | spring "punch in" motion and monospace text fitted to its box || [shaders](examples/shaders) | GPU shader layers composed with SVG: an SkSL background and a Shadertoy raymarcher clipped into a card |+| [shader-mode](examples/shader-mode) | a 31-second shader promo with reference audio, a moving panel wall, native preview footage and 18 GPU shader programs, rendered with Skia on Metal or Vulkan || [neon-triangle](examples/neon-triangle) | a minimal shader clip built to make banding and motion artifacts easy to spot || [hello-world](examples/hello-world) | a simple "hello world" video || [beta](examples/beta) | a complicated multi-scene example (our beta announce video) |diff --git a/examples/shader-mode/.gitignore b/examples/shader-mode/.gitignorenew file mode 100644index 00000000..dbf2118c--- /dev/null+++ b/examples/shader-mode/.gitignore@@ -0,0 +1,2 @@+dynamic_media/*+!dynamic_media/.gitkeepdiff --git a/examples/shader-mode/Cargo.toml b/examples/shader-mode/Cargo.tomlnew file mode 100644index 00000000..1e559d8e--- /dev/null+++ b/examples/shader-mode/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "shader-mode"+version = "1.2.0"+edition = "2024"+publish = false++[dependencies]+fframes = { workspace = true, features = ["compile-time-svgtree", "cli"] }++[target.'cfg(target_os = "macos")'.dependencies]+fframes_skia_renderer = { workspace = true, features = ["metal"] }+fframes_native_player = { workspace = true, features = ["metal"] }++[target.'cfg(not(target_os = "macos"))'.dependencies]+fframes_skia_renderer = { workspace = true, features = ["vulkan"] }+fframes_native_player.workspace = true++[target.'cfg(not(windows))'.dependencies]+fframes = { workspace = true, features = ["h264", "libav-agree-gpl", "build-portable"] }++[lints]+workspace = truediff --git a/examples/shader-mode/README.md b/examples/shader-mode/README.mdnew file mode 100644index 00000000..2ecc827f--- /dev/null+++ b/examples/shader-mode/README.md@@ -0,0 +1,56 @@+# Shader mode++A 932-frame, 1920×1080 Skia GPU example with 18 shaders, a 3D panel wall,+native preview footage and an animated fframes wordmark. Preview and rendering+run at 30 fps, using Metal on macOS and Vulkan elsewhere.++## Run++Place the soundtrack at `dynamic_media/reference-audio.wav`. To show the recorded+scrubbing, also provide `dynamic_media/native-scrubbing.mp4` (1920×1124 at 30 fps,+at least 71 frames). When the recording is absent, the bundled poster is used.+These runtime media files are kept outside Git.++From the repository root:++```sh+cargo run --release -p shader-mode -- preview+cargo run --release -p shader-mode -- preview 8.5s+```++The second command starts near the panel-wall animation. To export a video:++```sh+cargo run --release -p shader-mode -- render -o examples/shader-mode/output/shader-mode.mp4+```++`src/edit.rs` defines the scenes. `media/` contains the fonts, shader textures and+fallback poster used by the renderer. No Python scripts are needed to build or run.++## Upstream license++Parts of the shaders are adapted from+[Shader Effects Inc.](https://github.com/shader-effects-inc/shaders/tree/935f71a7789f0e07811dfe6fd0d8f707e9848238)+under the following license:++MIT License++Copyright (c) 2026 Shader Effects Inc.++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/examples/shader-mode/dynamic_media/.gitkeep b/examples/shader-mode/dynamic_media/.gitkeepnew file mode 100644index 00000000..e69de29bdiff --git a/examples/shader-mode/media/DMSans-Medium.ttf b/examples/shader-mode/media/DMSans-Medium.ttfnew file mode 100644index 00000000..fc8a5ebdBinary files /dev/null and b/examples/shader-mode/media/DMSans-Medium.ttf differdiff --git a/examples/shader-mode/media/InstrumentSerif-Italic.ttf b/examples/shader-mode/media/InstrumentSerif-Italic.ttfnew file mode 100644index 00000000..192c3edaBinary files /dev/null and b/examples/shader-mode/media/InstrumentSerif-Italic.ttf differdiff --git a/examples/shader-mode/media/JetBrainsMono-Regular.ttf b/examples/shader-mode/media/JetBrainsMono-Regular.ttfnew file mode 100644index 00000000..7d26f5a5Binary files /dev/null and b/examples/shader-mode/media/JetBrainsMono-Regular.ttf differdiff --git a/examples/shader-mode/media/binary-atlas.png b/examples/shader-mode/media/binary-atlas.pngnew file mode 100644index 00000000..3c4819e5Binary files /dev/null and b/examples/shader-mode/media/binary-atlas.png differdiff --git a/examples/shader-mode/media/catalog.png b/examples/shader-mode/media/catalog.pngnew file mode 100644index 00000000..91162bc6Binary files /dev/null and b/examples/shader-mode/media/catalog.png differdiff --git a/examples/shader-mode/media/fframes-sdf.png b/examples/shader-mode/media/fframes-sdf.pngnew file mode 100644index 00000000..053d30c5Binary files /dev/null and b/examples/shader-mode/media/fframes-sdf.png differdiff --git a/examples/shader-mode/media/glyph-atlas.png b/examples/shader-mode/media/glyph-atlas.pngnew file mode 100644index 00000000..34d54048Binary files /dev/null and b/examples/shader-mode/media/glyph-atlas.png differdiff --git a/examples/shader-mode/media/native-preview-poster.jpg b/examples/shader-mode/media/native-preview-poster.jpgnew file mode 100644index 00000000..75a1094dBinary files /dev/null and b/examples/shader-mode/media/native-preview-poster.jpg differdiff --git a/examples/shader-mode/src/catalog.rs b/examples/shader-mode/src/catalog.rsnew file mode 100644index 00000000..a0527965--- /dev/null+++ b/examples/shader-mode/src/catalog.rs@@ -0,0 +1,325 @@+//! Separate textured cards in camera space. Geometry is prepared once; Skia+//! projects and samples each card on the GPU, within its visible screen bounds.++use std::fmt::Write;++use fframes::{FFramesContext, Frame, Shader, ShaderUniforms, Svgr};++#[path = "catalog_layout.rs"]+mod layout;++type V3 = [f32; 3];+const PIXELS_PER_UNIT: f32 = 768.0;+const FOCAL: f32 = 1.6 * 1080.0;++fn add(a: V3, b: V3) -> V3 {+ std::array::from_fn(|i| a[i] + b[i])+}+fn sub(a: V3, b: V3) -> V3 {+ std::array::from_fn(|i| a[i] - b[i])+}+fn mul(a: V3, s: f32) -> V3 {+ a.map(|v| v * s)+}+fn turn(mut p: V3, a: usize, b: usize, angle: f32) -> V3 {+ let (s, c) = angle.sin_cos();+ (p[a], p[b]) = (c * p[a] - s * p[b], s * p[a] + c * p[b]);+ p+}+fn smooth(start: f32, end: f32, value: f32) -> f32 {+ let t = ((value - start) / (end - start)).clamp(0.0, 1.0);+ t * t * (3.0 - 2.0 * t)+}+fn random(index: usize, salt: usize) -> f32 {+ ((index * 73 + salt * 151 + index * index * 17) % 997) as f32 / 997.0+}++#[derive(Clone, Copy, Debug)]+struct Pose {+ center: V3,+ right: V3,+ down: V3,+}++impl Pose {+ fn world(index: usize, frame: f32) -> Self {+ let [x, y, w, h] = layout::RECTS[index];+ // Reference frames 280–295: different cards release at slightly+ // different times, open gaps, and overlap at different depths.+ let amount = smooth(23.0 + random(index, 1) * 3.0, 38.0, frame);+ let drift = smooth(36.0, 49.0, frame);+ let r = |salt| random(index, salt) * 2.0 - 1.0;+ let mut angles = [r(2) * 0.24, r(3) * 0.28, r(4) * 0.060];+ let mut offset = [r(5) * 0.042, r(6) * 0.035, r(7) * 0.19 - 0.035];+ offset[1] += drift * (0.018 + random(index, 8) * 0.035);+ if index == layout::PORTAL_TILE {+ angles = [0.10, -0.13, 0.045];+ offset = [-0.01, 0.015, -0.13];+ }+ let rotate = |p| {+ let p = turn(p, 1, 2, angles[0] * amount);+ let p = turn(p, 0, 2, angles[1] * amount);+ turn(p, 0, 1, angles[2] * amount)+ };+ Self {+ center: add(+ [+ (x + w * 0.5) / PIXELS_PER_UNIT,+ (y + h * 0.5) / PIXELS_PER_UNIT,+ 0.0,+ ],+ mul(offset, amount),+ ),+ right: rotate([1.0, 0.0, 0.0]),+ down: rotate([0.0, 1.0, 0.0]),+ }+ }++ fn point(self, x: f32, y: f32) -> V3 {+ add(self.center, add(mul(self.right, x), mul(self.down, y)))+ }+}++struct Camera {+ origin: V3,+ angles: V3,+}++impl Camera {+ fn new(frame: f32) -> Self {+ let entering = (1.0 - (frame / 18.0).clamp(0.0, 1.0)).powi(2);+ let leaving = smooth(39.0, 47.0, frame) * (1.0 - smooth(48.0, 50.0, frame));+ let distance = if frame < 18.0 {+ 2.25 - 2.01 * entering+ } else if frame < 43.0 {+ 2.25+ } else if frame < 48.0 {+ 2.25 - 1.80 * ((frame - 43.0) / 5.0).powf(1.6)+ } else if frame < 49.0 {+ 0.45 - 0.19 * (frame - 48.0)+ } else {+ 0.26 - 0.155 * (frame - 49.0).clamp(0.0, 1.0)+ };+ let [x, y, w, h] = layout::RECTS[layout::PORTAL_TILE];+ let hero = Pose::world(layout::PORTAL_TILE, frame).point(+ (layout::PORTAL[0] - x - w * 0.5) / PIXELS_PER_UNIT,+ (layout::PORTAL[1] - y - h * 0.5) / PIXELS_PER_UNIT,+ );+ let base = [+ (2360.0 - 100.0 * entering) / PIXELS_PER_UNIT,+ 1100.0 / PIXELS_PER_UNIT,+ 0.0,+ ];+ let target = add(base, mul(sub(hero, base), smooth(40.0, 49.0, frame)));+ let angles = [+ 0.20 * entering - 0.10 * leaving,+ -0.48 * entering + 0.25 * leaving,+ 0.12 * entering - 0.025 * leaving,+ ];+ let forward = turn(turn([0.0, 0.0, 1.0], 0, 2, angles[1]), 1, 2, angles[2]);+ Self {+ origin: sub(target, mul(forward, distance)),+ angles,+ }+ }++ fn direction(&self, p: V3) -> V3 {+ let p = turn(p, 1, 2, -self.angles[2]);+ let p = turn(p, 0, 2, -self.angles[1]);+ turn(p, 0, 1, -self.angles[0])+ }++ fn pose(&self, pose: Pose) -> Pose {+ Pose {+ center: self.direction(sub(pose.center, self.origin)),+ right: self.direction(pose.right),+ down: self.direction(pose.down),+ }+ }+}++fn project(p: V3) -> [f32; 2] {+ [960.0 + FOCAL * p[0] / p[2], 540.0 + FOCAL * p[1] / p[2]]+}++#[derive(Debug)]+struct Card {+ index: usize,+ pose: Pose,+ motion: Pose,+ bounds: [f32; 4],+}++impl Card {+ fn new(index: usize, start: f32, end: f32) -> Option<Self> {+ let pose = Camera::new(start).pose(Pose::world(index, start));+ let last = Camera::new(end).pose(Pose::world(index, end));+ let [_, _, width, height] = layout::RECTS[index];+ let mut lo = [1920.0_f32, 1080.0_f32];+ let mut hi = [0.0_f32, 0.0_f32];+ for sample in [pose, last] {+ let corners = [(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)].map(|(x, y)| {+ sample.point(+ x * width / (2.0 * PIXELS_PER_UNIT),+ y * height / (2.0 * PIXELS_PER_UNIT),+ )+ });+ // Clip to the camera's near plane before projecting. During the+ // icon dive, the large hero card straddles that plane.+ for i in 0..4 {+ let a = corners[i];+ let b = corners[(i + 1) % 4];+ let mut points = [None, None];+ if a[2] >= 0.01 {+ points[0] = Some(a);+ }+ if (a[2] >= 0.01) != (b[2] >= 0.01) {+ points[1] = Some(add(a, mul(sub(b, a), (0.01 - a[2]) / (b[2] - a[2]))));+ }+ for point in points.into_iter().flatten() {+ let p = project(point);+ for axis in 0..2 {+ lo[axis] = lo[axis].min(p[axis]);+ hi[axis] = hi[axis].max(p[axis]);+ }+ }+ }+ }+ let x = (lo[0] - 5.0).floor().max(0.0);+ let y = (lo[1] - 5.0).floor().max(0.0);+ let w = (hi[0] + 5.0).ceil().min(1920.0) - x;+ let h = (hi[1] + 5.0).ceil().min(1080.0) - y;+ (w > 0.0 && h > 0.0).then_some(Self {+ index,+ pose,+ motion: Pose {+ center: sub(last.center, pose.center),+ right: sub(last.right, pose.right),+ down: sub(last.down, pose.down),+ },+ bounds: [x, y, w, h],+ })+ }+}++#[derive(Debug)]+struct CatalogFrame {+ cards: Vec<Card>,+ portal_clip: String,+ shutter: bool,+}++#[derive(Debug)]+pub(super) struct Catalog {+ frames: Vec<CatalogFrame>,+}++impl Catalog {+ pub(super) fn new() -> Self {+ let frames = (0..51)+ .map(|index| {+ let frame = index as f32;+ let shutter = index < 7 || (44..49).contains(&index);+ let exposure = if shutter { 0.35 } else { 0.0 };+ let mut cards: Vec<_> = (0..layout::RECTS.len())+ .filter_map(|i| {+ Card::new(i, (frame - exposure * 0.5).max(0.0), frame + exposure * 0.5)+ })+ .collect();+ cards.sort_by(|a, b| b.pose.center[2].total_cmp(&a.pose.center[2]));+ let mut portal_clip = String::new();+ if index >= 49 {+ let pose = Camera::new(frame).pose(Pose::world(layout::PORTAL_TILE, frame));+ let [x, y, w, h] = layout::RECTS[layout::PORTAL_TILE];+ for i in 0..96 {+ let angle = i as f32 * std::f32::consts::TAU / 96.0;+ let p = project(pose.point(+ (layout::PORTAL[0] - x - w * 0.5 + 23.0 * angle.cos())+ / PIXELS_PER_UNIT,+ (layout::PORTAL[1] - y - h * 0.5 + 23.0 * angle.sin())+ / PIXELS_PER_UNIT,+ ));+ let _ = write!(+ portal_clip,+ "{}{} {} ",+ if i == 0 { 'M' } else { 'L' },+ p[0],+ p[1]+ );+ }+ portal_clip.push('Z');+ }+ CatalogFrame {+ cards,+ portal_clip,+ shutter,+ }+ })+ .collect();+ Self { frames }+ }++ pub(super) fn render<'a>(+ &'a self,+ frame: &Frame,+ ctx: &FFramesContext<'a, '_>,+ shader: &Shader,+ ) -> Svgr<'a> {+ let Some(atlas) = ctx.get_image("catalog.png") else {+ return Svgr::empty();+ };+ let Some(state) = self.frames.get(frame.index) else {+ return Svgr::empty();+ };+ let cards: Vec<_> = state+ .cards+ .iter()+ .map(|card| {+ let [x, y, w, h] = card.bounds;+ let [ax, ay, aw, ah] = layout::RECTS[card.index];+ let mut uniforms = ShaderUniforms::new()+ .image("uMask", atlas)+ .float("uClock", frame.index as f32 * 1001.0 / 30000.0)+ .float("uProgress", frame.index as f32 / 51.0)+ .float("uVariant", 0.0)+ .float("uBeat", 0.0)+ .float("uShutter", if state.shutter { 1.0 } else { 0.0 })+ .float(+ "uHero",+ if card.index == layout::PORTAL_TILE {+ 1.0+ } else {+ 0.0+ },+ )+ .float2("uOrigin", x, y)+ .float2("uPortal", layout::PORTAL[0], layout::PORTAL[1])+ .float4("uAtlas", ax, ay, aw, ah);+ for (name, value) in [+ ("uCenter", card.pose.center),+ ("uRight", card.pose.right),+ ("uDown", card.pose.down),+ ("uCenterMotion", card.motion.center),+ ("uRightMotion", card.motion.right),+ ("uDownMotion", card.motion.down),+ ] {+ uniforms = uniforms.float3(name, value[0], value[1], value[2]);+ }+ let layer = shader.draw(frame, uniforms);+ fframes::svgr!(<image href={layer.href()} x={x} y={y} width={w} height={h} />)+ })+ .collect();+ let title = if state.portal_clip.is_empty() {+ Svgr::empty()+ } else {+ fframes::svgr!(+ <g>+ <defs><clipPath id="catalog-portal-title"><path d={state.portal_clip.as_str()} /></clipPath></defs>+ <text x="960" y="576" text-anchor="middle" clip-path="url(#catalog-portal-title)"+ font-family="DM Sans" font-weight="500" font-size="64" letter-spacing="-1.8" fill="#fcf5ff">"SkSL + SHADERTOY"</text>+ </g>+ )+ };+ fframes::svgr!(<g><rect width="1920" height="1080" fill="#08080a" />{cards}{title}</g>)+ }+}diff --git a/examples/shader-mode/src/catalog_layout.rs b/examples/shader-mode/src/catalog_layout.rsnew file mode 100644index 00000000..bbf9af93--- /dev/null+++ b/examples/shader-mode/src/catalog_layout.rs@@ -0,0 +1,161 @@+// Card rectangles in media/catalog.png.+pub(super) const PORTAL_TILE: usize = 85;+pub(super) const PORTAL: [f32; 2] = [2605.0, 1088.0];+pub(super) const RECTS: [[f32; 4]; 156] = [+ [-175.0, 5.0, 438.0, 114.0],+ [275.0, 5.0, 518.0, 114.0],+ [805.0, 5.0, 438.0, 114.0],+ [1255.0, 5.0, 438.0, 114.0],+ [1705.0, 5.0, 452.0, 114.0],+ [2169.0, 5.0, 438.0, 114.0],+ [2619.0, 5.0, 438.0, 114.0],+ [3069.0, 5.0, 438.0, 114.0],+ [3519.0, 5.0, 438.0, 114.0],+ [3969.0, 5.0, 518.0, 114.0],+ [-15.0, 133.0, 438.0, 114.0],+ [435.0, 133.0, 438.0, 114.0],+ [885.0, 133.0, 438.0, 114.0],+ [1335.0, 133.0, 562.0, 114.0],+ [1909.0, 133.0, 438.0, 114.0],+ [2359.0, 133.0, 438.0, 114.0],+ [2809.0, 133.0, 438.0, 114.0],+ [3259.0, 133.0, 438.0, 114.0],+ [3709.0, 133.0, 438.0, 114.0],+ [-240.0, 261.0, 438.0, 114.0],+ [210.0, 261.0, 496.0, 114.0],+ [718.0, 261.0, 438.0, 114.0],+ [1168.0, 261.0, 438.0, 114.0],+ [1618.0, 261.0, 438.0, 114.0],+ [2068.0, 261.0, 438.0, 114.0],+ [2518.0, 261.0, 438.0, 114.0],+ [2968.0, 261.0, 438.0, 114.0],+ [3418.0, 261.0, 438.0, 114.0],+ [3868.0, 261.0, 496.0, 114.0],+ [-80.0, 389.0, 438.0, 114.0],+ [370.0, 389.0, 438.0, 114.0],+ [820.0, 389.0, 438.0, 114.0],+ [1270.0, 389.0, 438.0, 114.0],+ [1720.0, 389.0, 518.0, 114.0],+ [2250.0, 389.0, 438.0, 114.0],+ [2700.0, 389.0, 438.0, 114.0],+ [3150.0, 389.0, 452.0, 114.0],+ [3614.0, 389.0, 438.0, 114.0],+ [4064.0, 389.0, 438.0, 114.0],+ [-175.0, 517.0, 438.0, 114.0],+ [275.0, 517.0, 438.0, 114.0],+ [725.0, 517.0, 438.0, 114.0],+ [1175.0, 517.0, 438.0, 114.0],+ [1625.0, 517.0, 438.0, 114.0],+ [2075.0, 517.0, 438.0, 114.0],+ [2525.0, 517.0, 562.0, 114.0],+ [3099.0, 517.0, 438.0, 114.0],+ [3549.0, 517.0, 438.0, 114.0],+ [3999.0, 517.0, 438.0, 114.0],+ [-15.0, 645.0, 438.0, 114.0],+ [435.0, 645.0, 438.0, 114.0],+ [885.0, 645.0, 438.0, 114.0],+ [1335.0, 645.0, 438.0, 114.0],+ [1785.0, 645.0, 496.0, 114.0],+ [2293.0, 645.0, 438.0, 114.0],+ [2743.0, 645.0, 438.0, 114.0],+ [3193.0, 645.0, 438.0, 114.0],+ [3643.0, 645.0, 438.0, 114.0],+ [4093.0, 645.0, 438.0, 114.0],+ [-240.0, 773.0, 438.0, 114.0],+ [210.0, 773.0, 438.0, 114.0],+ [660.0, 773.0, 452.0, 114.0],+ [1124.0, 773.0, 438.0, 114.0],+ [1574.0, 773.0, 438.0, 114.0],+ [2024.0, 773.0, 438.0, 114.0],+ [2474.0, 773.0, 438.0, 114.0],+ [2924.0, 773.0, 518.0, 114.0],+ [3454.0, 773.0, 438.0, 114.0],+ [3904.0, 773.0, 438.0, 114.0],+ [-80.0, 901.0, 438.0, 114.0],+ [370.0, 901.0, 562.0, 114.0],+ [944.0, 901.0, 438.0, 114.0],+ [1394.0, 901.0, 438.0, 114.0],+ [1844.0, 901.0, 438.0, 114.0],+ [2294.0, 901.0, 438.0, 114.0],+ [2744.0, 901.0, 438.0, 114.0],+ [3194.0, 901.0, 438.0, 114.0],+ [3644.0, 901.0, 438.0, 114.0],+ [4094.0, 901.0, 562.0, 114.0],+ [-175.0, 1029.0, 438.0, 114.0],+ [275.0, 1029.0, 438.0, 114.0],+ [725.0, 1029.0, 438.0, 114.0],+ [1175.0, 1029.0, 438.0, 114.0],+ [1625.0, 1029.0, 438.0, 114.0],+ [2075.0, 1029.0, 438.0, 114.0],+ [2525.0, 1029.0, 518.0, 114.0],+ [3055.0, 1029.0, 496.0, 114.0],+ [3563.0, 1029.0, 438.0, 114.0],+ [4013.0, 1029.0, 438.0, 114.0],+ [-15.0, 1157.0, 438.0, 114.0],+ [435.0, 1157.0, 438.0, 114.0],+ [885.0, 1157.0, 518.0, 114.0],+ [1415.0, 1157.0, 438.0, 114.0],+ [1865.0, 1157.0, 438.0, 114.0],+ [2315.0, 1157.0, 452.0, 114.0],+ [2779.0, 1157.0, 438.0, 114.0],+ [3229.0, 1157.0, 438.0, 114.0],+ [3679.0, 1157.0, 438.0, 114.0],+ [-240.0, 1285.0, 438.0, 114.0],+ [210.0, 1285.0, 438.0, 114.0],+ [660.0, 1285.0, 438.0, 114.0],+ [1110.0, 1285.0, 438.0, 114.0],+ [1560.0, 1285.0, 562.0, 114.0],+ [2134.0, 1285.0, 438.0, 114.0],+ [2584.0, 1285.0, 438.0, 114.0],+ [3034.0, 1285.0, 438.0, 114.0],+ [3484.0, 1285.0, 438.0, 114.0],+ [3934.0, 1285.0, 438.0, 114.0],+ [-80.0, 1413.0, 438.0, 114.0],+ [370.0, 1413.0, 438.0, 114.0],+ [820.0, 1413.0, 496.0, 114.0],+ [1328.0, 1413.0, 438.0, 114.0],+ [1778.0, 1413.0, 438.0, 114.0],+ [2228.0, 1413.0, 438.0, 114.0],+ [2678.0, 1413.0, 438.0, 114.0],+ [3128.0, 1413.0, 438.0, 114.0],+ [3578.0, 1413.0, 438.0, 114.0],+ [4028.0, 1413.0, 438.0, 114.0],+ [-175.0, 1541.0, 452.0, 114.0],+ [289.0, 1541.0, 438.0, 114.0],+ [739.0, 1541.0, 438.0, 114.0],+ [1189.0, 1541.0, 438.0, 114.0],+ [1639.0, 1541.0, 438.0, 114.0],+ [2089.0, 1541.0, 518.0, 114.0],+ [2619.0, 1541.0, 438.0, 114.0],+ [3069.0, 1541.0, 438.0, 114.0],+ [3519.0, 1541.0, 452.0, 114.0],+ [3983.0, 1541.0, 438.0, 114.0],+ [-15.0, 1669.0, 438.0, 114.0],+ [435.0, 1669.0, 438.0, 114.0],+ [885.0, 1669.0, 438.0, 114.0],+ [1335.0, 1669.0, 438.0, 114.0],+ [1785.0, 1669.0, 438.0, 114.0],+ [2235.0, 1669.0, 438.0, 114.0],+ [2685.0, 1669.0, 438.0, 114.0],+ [3135.0, 1669.0, 562.0, 114.0],+ [3709.0, 1669.0, 438.0, 114.0],+ [-240.0, 1797.0, 438.0, 114.0],+ [210.0, 1797.0, 438.0, 114.0],+ [660.0, 1797.0, 438.0, 114.0],+ [1110.0, 1797.0, 438.0, 114.0],+ [1560.0, 1797.0, 438.0, 114.0],+ [2010.0, 1797.0, 496.0, 114.0],+ [2518.0, 1797.0, 438.0, 114.0],+ [2968.0, 1797.0, 438.0, 114.0],+ [3418.0, 1797.0, 438.0, 114.0],+ [3868.0, 1797.0, 438.0, 114.0],+ [-80.0, 1925.0, 518.0, 114.0],+ [450.0, 1925.0, 438.0, 114.0],+ [900.0, 1925.0, 438.0, 114.0],+ [1350.0, 1925.0, 452.0, 114.0],+ [1814.0, 1925.0, 438.0, 114.0],+ [2264.0, 1925.0, 438.0, 114.0],+ [2714.0, 1925.0, 438.0, 114.0],+ [3164.0, 1925.0, 438.0, 114.0],+ [3614.0, 1925.0, 518.0, 114.0],+];diff --git a/examples/shader-mode/src/edit.rs b/examples/shader-mode/src/edit.rsnew file mode 100644index 00000000..ad66b67e--- /dev/null+++ b/examples/shader-mode/src/edit.rs@@ -0,0 +1,357 @@+//! The reference edit, in its original 30000/1001 source-frame timebase.+//! Color hard cuts are individual shots; continuous camera moves stay inside a shot.+//! The integer-fps renderer produces these same 932 frames at 30 fps. The export+//! tool restores the rational timestamps and copies the reference AAC packets.++use crate::Effect;++pub(crate) const SOURCE_FRAMES: usize = 932;+pub(crate) const SOURCE_FPS_NUM: usize = 30000;+pub(crate) const SOURCE_FPS_DEN: usize = 1001;++#[derive(Clone, Copy, Debug)]+pub(crate) struct ShotSpec {+ pub name: &'static str,+ pub start: usize,+ pub end: usize,+ pub effect: Option<Effect>,+ pub variant: u8,+ pub clock_start: usize,+}++impl ShotSpec {+ pub const fn frames(self) -> usize {+ self.end - self.start+ }+}++pub(crate) const SHOTS: &[ShotSpec] = &[+ ShotSpec {+ name: "BlackLead",+ start: 0,+ end: 6,+ effect: None,+ variant: 0,+ clock_start: 0,+ },+ ShotSpec {+ name: "Boot",+ start: 6,+ end: 26,+ effect: Some(Effect::Binary),+ variant: 0,+ clock_start: 6,+ },+ ShotSpec {+ name: "Glass",+ start: 26,+ end: 57,+ effect: Some(Effect::Glass),+ variant: 0,+ clock_start: 26,+ },+ ShotSpec {+ name: "GlassAmber",+ start: 57,+ end: 82,+ effect: Some(Effect::Glass),+ variant: 1,+ clock_start: 26,+ },+ ShotSpec {+ name: "Chrome",+ start: 82,+ end: 91,+ effect: Some(Effect::Material),+ variant: 0,+ clock_start: 82,+ },+ ShotSpec {+ name: "Crystal",+ start: 91,+ end: 97,+ effect: Some(Effect::Material),+ variant: 4,+ clock_start: 82,+ },+ ShotSpec {+ name: "Gold",+ start: 97,+ end: 104,+ effect: Some(Effect::Material),+ variant: 1,+ clock_start: 82,+ },+ ShotSpec {+ name: "Ceramic",+ start: 104,+ end: 111,+ effect: Some(Effect::Material),+ variant: 5,+ clock_start: 82,+ },+ ShotSpec {+ name: "Carbon",+ start: 111,+ end: 119,+ effect: Some(Effect::Material),+ variant: 2,+ clock_start: 82,+ },+ ShotSpec {+ name: "ChromeSoft",+ start: 119,+ end: 126,+ effect: Some(Effect::Material),+ variant: 0,+ clock_start: 82,+ },+ ShotSpec {+ name: "Pixels",+ start: 126,+ end: 132,+ effect: Some(Effect::Material),+ variant: 3,+ clock_start: 82,+ },+ ShotSpec {+ name: "PrismGlass",+ start: 132,+ end: 141,+ effect: Some(Effect::Material),+ variant: 6,+ clock_start: 82,+ },+ ShotSpec {+ name: "OpenSource",+ start: 141,+ end: 209,+ effect: Some(Effect::LiquidChrome),+ variant: 0,+ clock_start: 141,+ },+ ShotSpec {+ name: "OpenSourceHold",+ start: 209,+ end: 222,+ effect: Some(Effect::LiquidChrome),+ variant: 0,+ clock_start: 141,+ },+ ShotSpec {+ name: "Rose",+ start: 222,+ end: 229,+ effect: Some(Effect::Obsidian),+ variant: 1,+ clock_start: 222,+ },+ ShotSpec {+ name: "Tunnel",+ start: 229,+ end: 238,+ effect: Some(Effect::Tunnel),+ variant: 0,+ clock_start: 229,+ },+ ShotSpec {+ name: "Halftone",+ start: 238,+ end: 256,+ effect: Some(Effect::Halftone),+ variant: 0,+ clock_start: 238,+ },+ ShotSpec {+ name: "ShaderLibrary",+ start: 256,+ end: 307,+ effect: Some(Effect::Catalog),+ variant: 0,+ clock_start: 256,+ },+ ShotSpec {+ name: "Gradient",+ start: 307,+ end: 344,+ effect: Some(Effect::Gradient),+ variant: 0,+ clock_start: 307,+ },+ ShotSpec {+ name: "Ascii",+ start: 344,+ end: 357,+ effect: Some(Effect::Ascii),+ variant: 1,+ clock_start: 344,+ },+ ShotSpec {+ name: "Particles",+ start: 357,+ end: 377,+ effect: Some(Effect::Particles),+ variant: 0,+ clock_start: 357,+ },+ ShotSpec {+ name: "Obsidian",+ start: 377,+ end: 391,+ effect: Some(Effect::Obsidian),+ variant: 0,+ clock_start: 377,+ },+ ShotSpec {+ name: "Silver",+ start: 391,+ end: 397,+ effect: Some(Effect::Spectral),+ variant: 2,+ clock_start: 391,+ },+ ShotSpec {+ name: "AuroraGreen",+ start: 397,+ end: 400,+ effect: Some(Effect::Aurora),+ variant: 1,+ clock_start: 391,+ },+ ShotSpec {+ name: "AuroraPurple",+ start: 400,+ end: 403,+ effect: Some(Effect::Aurora),+ variant: 2,+ clock_start: 391,+ },+ ShotSpec {+ name: "AuroraAqua",+ start: 403,+ end: 407,+ effect: Some(Effect::Aurora),+ variant: 3,+ clock_start: 391,+ },+ ShotSpec {+ name: "AuroraOrange",+ start: 407,+ end: 410,+ effect: Some(Effect::Aurora),+ variant: 4,+ clock_start: 391,+ },+ ShotSpec {+ name: "BlackBreak",+ start: 410,+ end: 417,+ effect: None,+ variant: 0,+ clock_start: 410,+ },+ ShotSpec {+ name: "Flow",+ start: 417,+ end: 447,+ effect: Some(Effect::Flow),+ variant: 0,+ clock_start: 417,+ },+ ShotSpec {+ name: "EmbossBlue",+ start: 447,+ end: 459,+ effect: Some(Effect::Emboss),+ variant: 0,+ clock_start: 447,+ },+ ShotSpec {+ name: "EmbossGreen",+ start: 459,+ end: 471,+ effect: Some(Effect::Emboss),+ variant: 1,+ clock_start: 447,+ },+ ShotSpec {+ name: "EmbossOrange",+ start: 471,+ end: 483,+ effect: Some(Effect::Emboss),+ variant: 2,+ clock_start: 447,+ },+ ShotSpec {+ name: "EmbossPearl",+ start: 483,+ end: 496,+ effect: Some(Effect::Emboss),+ variant: 3,+ clock_start: 447,+ },+ ShotSpec {+ name: "NativePreview",+ start: 496,+ end: 567,+ effect: Some(Effect::Preview),+ variant: 0,+ clock_start: 496,+ },+ ShotSpec {+ name: "ShaderModeEditor",+ start: 567,+ end: 586,+ effect: Some(Effect::Spectral),+ variant: 0,+ clock_start: 567,+ },+ ShotSpec {+ name: "ShaderModeZoom",+ start: 586,+ end: 610,+ effect: Some(Effect::Spectral),+ variant: 0,+ clock_start: 567,+ },+ ShotSpec {+ name: "ShaderMode",+ start: 610,+ end: 626,+ effect: Some(Effect::Spectral),+ variant: 0,+ clock_start: 567,+ },+ ShotSpec {+ name: "ShaderModeWide",+ start: 626,+ end: 640,+ effect: Some(Effect::Spectral),+ variant: 0,+ clock_start: 567,+ },+ ShotSpec {+ name: "BlackPause",+ start: 640,+ end: 654,+ effect: None,+ variant: 0,+ clock_start: 640,+ },+ ShotSpec {+ name: "Eclipse",+ start: 654,+ end: 849,+ effect: Some(Effect::Eclipse),+ variant: 0,+ clock_start: 654,+ },+ ShotSpec {+ name: "BlackTail",+ start: 849,+ end: 932,+ effect: None,+ variant: 0,+ clock_start: 849,+ },+];diff --git a/examples/shader-mode/src/lib.rs b/examples/shader-mode/src/lib.rsnew file mode 100644index 00000000..75fe6120--- /dev/null+++ b/examples/shader-mode/src/lib.rs@@ -0,0 +1,314 @@+//! A source-frame-matched shader promo rendered by Skia, with native preview recordings.++mod catalog;+mod edit;+mod outro;+mod titles;+mod transitions;++use fframes::{+ AudioMap, AudioTimestamp, AudioTrack, Color, Duration, FFramesContext, FFramesSyncedVideoFrame,+ Frame, Scene, Scenes, Shader, ShaderUniforms, Svgr, SyncVideoFrameInput, Video,+};++fframes::include_media_dir!(pub struct ShaderModeMedia, "examples/shader-mode/media");++const COMMON: &str = include_str!("shaders/common.sksl");+const SOURCE_EFFECTS: &str = include_str!("shaders/source-effects.sksl");++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Effect {+ Ascii,+ Glass,+ Material,+ LiquidChrome,+ Tunnel,+ Halftone,+ Gradient,+ Particles,+ Obsidian,+ Aurora,+ Flow,+ Emboss,+ Rays,+ Spectral,+ Eclipse,+ Catalog,+ Preview,+ Binary,+}++impl Effect {+ const ALL: [Self; 18] = [+ Self::Ascii,+ Self::Glass,+ Self::Material,+ Self::LiquidChrome,+ Self::Tunnel,+ Self::Halftone,+ Self::Gradient,+ Self::Particles,+ Self::Obsidian,+ Self::Aurora,+ Self::Flow,+ Self::Emboss,+ Self::Rays,+ Self::Spectral,+ Self::Eclipse,+ Self::Catalog,+ Self::Preview,+ Self::Binary,+ ];++ fn source(self) -> &'static str {+ match self {+ Self::Ascii => include_str!("shaders/ascii.sksl"),+ Self::Glass => include_str!("shaders/glass.sksl"),+ Self::Material => include_str!("shaders/material.sksl"),+ Self::LiquidChrome => include_str!("shaders/liquid-chrome.sksl"),+ Self::Tunnel => include_str!("shaders/tunnel.glsl"),+ Self::Halftone => include_str!("shaders/halftone.sksl"),+ Self::Gradient => include_str!("shaders/gradient.sksl"),+ Self::Particles => include_str!("shaders/particles.sksl"),+ Self::Obsidian => include_str!("shaders/obsidian.sksl"),+ Self::Aurora => include_str!("shaders/aurora.sksl"),+ Self::Flow => include_str!("shaders/flow.sksl"),+ Self::Emboss => include_str!("shaders/emboss.sksl"),+ Self::Rays => include_str!("shaders/rays.sksl"),+ Self::Spectral => include_str!("shaders/spectral.sksl"),+ Self::Eclipse => include_str!("shaders/eclipse.sksl"),+ Self::Catalog => include_str!("shaders/catalog.sksl"),+ Self::Preview => include_str!("shaders/preview.sksl"),+ Self::Binary => include_str!("shaders/binary-intro.sksl"),+ }+ }++ fn mask(self) -> Option<&'static str> {+ match self {+ Self::Ascii => Some("glyph-atlas.png"),+ Self::Binary => Some("binary-atlas.png"),+ Self::Halftone | Self::Emboss => Some("fframes-sdf.png"),+ Self::Catalog => Some("catalog.png"),+ _ => None,+ }+ }++ fn shader(self) -> Shader {+ if self == Self::Tunnel {+ Shader::shadertoy(format!(+ "uniform float uClock;\n{}",+ self.source().replace("iTime", "uClock")+ ))+ } else {+ let sculpture = if matches!(self, Self::LiquidChrome | Self::Obsidian) {+ include_str!("shaders/sculpture.sksl")+ } else {+ ""+ };+ let gradient = if matches!(self, Self::Gradient | Self::Catalog) {+ include_str!("shaders/gradient-shared.sksl")+ } else {+ ""+ };+ Shader::sksl(+ format!(+ "{COMMON}\n{SOURCE_EFFECTS}\n{sculpture}\n{gradient}\n{}",+ self.source()+ )+ .replace("iTime", "uClock"),+ )+ }+ }+}++use edit::{SHOTS, ShotSpec};++#[derive(Debug)]+struct Shot {+ spec: ShotSpec,+ shader: Option<Shader>,+ outro: Option<outro::Outro>,+ opening_overlay: Option<Shader>,+ catalog: Option<catalog::Catalog>,+}++impl Scene for Shot {+ fn name(&self) -> &'static str {+ self.spec.name+ }++ fn duration(&self) -> Duration<'_> {+ Duration::Frames(self.spec.frames())+ }++ fn render_frame<'a>(&'a self, mut frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+ let Some(shader) = &self.shader else {+ return Svgr::empty();+ };+ let progress = frame.index as f32 / self.spec.frames() as f32;+ let source_index = frame.global_index;+ // Keep geometry continuous through color/material cuts, while progress is+ // local to the edit segment. Use uClock for the source's actual rational clock.+ frame.index = source_index - self.spec.clock_start;+ if let Some(catalog) = &self.catalog {+ return transitions::apply(+ source_index,+ self.spec.name,+ catalog.render(&frame, ctx, shader),+ );+ }+ let seconds =+ frame.index as f32 * edit::SOURCE_FPS_DEN as f32 / edit::SOURCE_FPS_NUM as f32;+ let mut uniforms = ShaderUniforms::new()+ .float("uClock", seconds)+ .float("uProgress", progress)+ .float("uVariant", f32::from(self.spec.variant))+ .float("uBeat", (-(seconds % 0.5) * 12.0).exp());+ if let Some(name) = self.spec.effect.and_then(Effect::mask) {+ let Some(mask) = ctx.get_image(name) else {+ return Svgr::empty();+ };+ uniforms = uniforms.image("uMask", mask);+ }+ if self.spec.effect == Some(Effect::Preview) {+ let file = "native-scrubbing.mp4";+ let mut recording_frame = frame.clone();+ recording_frame.index = source_index - 496;+ let input = SyncVideoFrameInput {+ looping: false,+ ..Default::default()+ };+ let recording = ctx+ .media_source+ .and_then(|media| media.resolve_video(file))+ .and_then(|_| recording_frame.get_synced_video_frame(ctx, file, &input));+ if let Some(recording) = recording {+ let image = recording.into_image();+ uniforms = uniforms.image("uRecording", &image).float2(+ "uRecordingSize",+ recording.width() as f32,+ recording.height() as f32,+ );+ } else if let Some(poster) = ctx.get_image("native-preview-poster.jpg") {+ // Use the bundled poster when the recording is unavailable.+ uniforms =+ uniforms+ .image("uRecording", poster)+ .float2("uRecordingSize", 1920.0, 1124.0);+ } else {+ return Svgr::empty();+ }+ }+ let layer = shader.draw(&frame, uniforms);+ let title_name = match self.spec.name {+ "GlassAmber" => "Glass",+ "OpenSourceHold" => "OpenSource",+ "ShaderModeEditor" | "ShaderModeZoom" | "ShaderModeWide" => "ShaderMode",+ other => other,+ };+ let titles = match &self.outro {+ Some(outro) => outro.render(&mut frame, ctx),+ None => titles::render(title_name, &frame),+ };+ let titles = if self.spec.name == "Glass" && source_index < 35 {+ let opacity = ((source_index as f32 - 31.0) / 4.0).clamp(0.0, 1.0);+ fframes::svgr!(<g opacity={opacity}>{titles}</g>)+ } else {+ titles+ };+ let composition = fframes::svgr!(+ <g>+ <image href={layer.href()} x="0" y="0" width="1920" height="1080" />+ {titles}+ </g>+ );+ let composition = transitions::apply(source_index, self.spec.name, composition);+ if source_index < 33+ && let Some(opening) = &self.opening_overlay+ && let Some(atlas) = ctx.get_image("binary-atlas.png")+ {+ let layer = opening.draw(+ &frame,+ ShaderUniforms::new()+ .float("uClock", (source_index - 6) as f32 * 1001.0 / 30000.0)+ .float("uVariant", 1.0)+ .image("uMask", atlas),+ );+ return fframes::svgr!(+ <g>+ {composition}+ <image href={layer.href()} width="1920" height="1080" />+ </g>+ );+ }+ composition+ }+}++/// Native Skia showcase: 932 source frames, 1920×1080.+#[derive(Debug)]+pub struct ShaderMode {+ shots: Vec<Shot>,+}++impl ShaderMode {+ /// Creates shader definitions once; Skia compiles and caches them on first use.+ pub fn new() -> Self {+ let shaders = Effect::ALL.map(Effect::shader);+ let shots = SHOTS+ .iter()+ .copied()+ .map(|spec| Shot {+ shader: spec.effect.map(|effect| shaders[effect as usize].clone()),+ outro: (spec.name == "Eclipse").then(outro::Outro::default),+ opening_overlay: (spec.name == "Glass")+ .then(|| shaders[Effect::Binary as usize].clone()),+ catalog: (spec.effect == Some(Effect::Catalog)).then(catalog::Catalog::new),+ spec,+ })+ .collect();+ Self { shots }+ }+}++impl Default for ShaderMode {+ fn default() -> Self {+ Self::new()+ }+}++impl Video for ShaderMode {+ const FPS: usize = 30;+ const WIDTH: usize = 1920;+ const HEIGHT: usize = 1080;+ const BACKGROUND_COLOR: Color = Color::BLACK;++ fn duration(&self) -> Duration<'_> {+ Duration::Frames(edit::SOURCE_FRAMES)+ }++ fn define_scenes(&self) -> Scenes<'_> {+ Scenes::from(+ self.shots+ .iter()+ .map(|shot| shot as &dyn Scene)+ .collect::<Vec<_>>(),+ )+ }++ fn audio(&self) -> AudioMap<'_> {+ AudioMap::from([AudioTrack::new(+ "reference-audio.wav",+ AudioTimestamp::Second(0.0)..AudioTimestamp::Eof,+ )])+ }++ fn render_frame<'a>(&'a self, frame: Frame, ctx: &FFramesContext<'a, '_>) -> Svgr<'a> {+ fframes::svgr!(+ <svg xmlns="http://www.w3.org/2000/svg" width="1920" height="1080" viewBox="0 0 1920 1080">+ <rect width="1920" height="1080" fill="#000" />+ {ctx.render_scenes(&frame)}+ </svg>+ )+ }+}diff --git a/examples/shader-mode/src/main.rs b/examples/shader-mode/src/main.rsnew file mode 100644index 00000000..2400f7b6--- /dev/null+++ b/examples/shader-mode/src/main.rs@@ -0,0 +1,61 @@+use std::process::ExitCode;++use fframes::{+ AudioMixOptions, CombinedMediaProvider, EncoderOptions, MediaDirectory, MediaProvider,+ RenderOptions, StaticMediaProvider, Video, cli,+};+use fframes_skia_renderer::{SkiaFFramesRenderer, SkiaPipelineConfig};+use shader_mode::{ShaderMode, ShaderModeMedia};++fn run() -> Result<ExitCode, Box<dyn std::error::Error>> {+ let media = ShaderModeMedia::prepare()?;+ let folder = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("dynamic_media");++ let directory = MediaDirectory::read_folder(folder)?;+ let dynamic = directory.process_media_source()?;+ let all = CombinedMediaProvider::from([&media as &dyn MediaProvider, &dynamic]);+ let video = ShaderMode::new();+ #[cfg(target_os = "macos")]+ let gpu =+ fframes_skia_renderer::metal::SkiaMetalCtx::new(ShaderMode::WIDTH, ShaderMode::HEIGHT)?;+ #[cfg(not(target_os = "macos"))]+ let gpu =+ fframes_skia_renderer::vulkan::SkiaVulkanCtx::new(ShaderMode::WIDTH, ShaderMode::HEIGHT)?;++ #[cfg(target_os = "macos")]+ let backend = SkiaFFramesRenderer::new_metal(&gpu, SkiaPipelineConfig::default())?;+ #[cfg(not(target_os = "macos"))]+ let backend = SkiaFFramesRenderer::new_vulkan(&gpu, SkiaPipelineConfig::default())?;++ Ok(cli::new(+ &video,+ RenderOptions {+ media: Some(&all),+ video_encoder_options: EncoderOptions {+ preferred_encoder: Some("libx264"),+ codec_params: Some(&[("crf", "17"), ("preset", "medium")]),+ ..Default::default()+ },+ // Play the source soundtrack in stereo, without gain or limiting.+ audio_mix: AudioMixOptions {+ limiter: None,+ ..Default::default()+ },+ ..Default::default()+ },+ )+ .backend(backend)+ .preview(fframes_native_player::cli_preview)+ .default_output(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("output/shader-mode.mp4"))+ .run())+}++fn main() -> ExitCode {+ match run() {+ Ok(code) => code,+ Err(error) => {+ eprintln!("shader-mode: {error}");+ ExitCode::FAILURE+ }+ }+}diff --git a/examples/shader-mode/src/outro.rs b/examples/shader-mode/src/outro.rsnew file mode 100644index 00000000..4f1faa4a--- /dev/null+++ b/examples/shader-mode/src/outro.rs@@ -0,0 +1,100 @@+//! Vector wordmark animation from `fframes-intro/src/scenes/outro.rs`.+//! Keep the intro's font, spring parameters, stagger and orange echo palette.++use std::sync::OnceLock;++use fframes::{FFramesContext, FontQuery, FontStyle, Frame, Svgr};++const FONT: &str = "Instrument Serif";+const WORD_SIZE: usize = 300;+const BEAT: f32 = 0.454_522;++#[derive(Debug, Default)]+pub(crate) struct Outro {+ widths: OnceLock<(f32, f32)>,+}++impl Outro {+ fn measure(&self, frame: &mut Frame, ctx: &FFramesContext<'_, '_>) -> (f32, f32) {+ if let Some(widths) = self.widths.get() {+ return *widths;+ }+ let font = FontQuery {+ family: FONT,+ size: WORD_SIZE,+ weight: 400,+ style: FontStyle::Italic,+ ..Default::default()+ };+ match (+ frame.text_width(ctx, font, "fframes"),+ frame.text_width(ctx, font, "f"),+ ) {+ (Some(word), Some(letter)) => *self.widths.get_or_init(|| (word as f32, letter as f32)),+ // Do not cache a fallback if fonts are temporarily unavailable.+ _ => (840.0, 84.0),+ }+ }++ pub(crate) fn render(&self, frame: &mut Frame, ctx: &FFramesContext<'_, '_>) -> Svgr<'static> {+ let seconds = frame.seconds();+ let beats = seconds / BEAT;+ let (width, letter_width) = self.measure(frame, ctx);+ let step = letter_width * 0.78;+ let total = width + step * 3.0;+ let x = 960.0 - total / 2.0 + step * 3.0;+ let y = 530.0;+ let word_opacity = spring(seconds, 260.0, 20.0).min(1.0);+ let word_scale = 1.0 + (1.0 - expo_out(beats / 0.5)) * 0.25;+ let echoes: Vec<Svgr> = ["#fb6a22", "#c4531c", "#8a3712"]+ .into_iter()+ .enumerate()+ .rev()+ .map(|(index, color)| {+ let index = index as f32;+ let amount = spring((beats - 0.5 - index * 0.5) * BEAT, 170.0, 15.0);+ let dx = -step * (index + 1.0) * amount;+ let opacity = amount.clamp(0.0, 1.0) * (1.0 - index * 0.18);+ fframes::svgr!(+ <text x={x + dx} y={y} font-family={FONT} font-style="italic"+ font-weight="400" font-size={WORD_SIZE} fill={color} opacity={opacity}>"f"</text>+ )+ })+ .collect();+ let tag = ((beats - 4.0) / 0.6).clamp(0.0, 1.0);++ fframes::svgr!(+ <g>+ {echoes}+ <g transform={format!("translate(960 {y}) scale({word_scale}) translate(-960 -{y})")}+ opacity={word_opacity}>+ <text x={x} y={y} font-family={FONT} font-style="italic"+ font-weight="400" font-size={WORD_SIZE} fill="#ece8e1">"fframes"</text>+ </g>+ <text x="960" y="636" text-anchor="middle" font-family="JetBrains Mono"+ font-size="30" letter-spacing="3" fill="#c6b4ef" opacity={tag}>"SHADER MODE"</text>+ </g>+ )+ }+}++// The same damped springs and exponential scale-in as fframes-intro/beat.rs.+fn spring(seconds: f32, stiffness: f32, damping: f32) -> f32 {+ if seconds <= 0.0 {+ return 0.0;+ }+ let natural = stiffness.sqrt();+ let ratio = damping / (2.0 * natural);+ let damped = natural * (1.0 - ratio * ratio).sqrt();+ 1.0 - (-ratio * natural * seconds).exp()+ * ((damped * seconds).cos() + ratio * natural / damped * (damped * seconds).sin())+}++fn expo_out(progress: f32) -> f32 {+ let progress = progress.clamp(0.0, 1.0);+ if progress >= 1.0 {+ 1.0+ } else {+ 1.0 - 2.0_f32.powf(-10.0 * progress)+ }+}diff --git a/examples/shader-mode/src/shaders/ascii.sksl b/examples/shader-mode/src/shaders/ascii.skslnew file mode 100644index 00000000..3c780bcf--- /dev/null+++ b/examples/shader-mode/src/shaders/ascii.sksl@@ -0,0 +1,23 @@+// asciiGrid / asciiAtlasUV / asciiCompose port from kit/stylizePaints.ts (MIT).+uniform shader uMask;+float3 asciiInput(float2 uv) {+ float2 p=(uv-.5)*float2(iResolution.x/iResolution.y,1);+ float warp=noise3(float3(p*2.3,iTime*.4));+ float ring=length(p+float2(.08,.02))-.34-warp*.10;+ float field=exp(-abs(ring)*10.0)*(.55+.45*noise3(float3(p*4.0,iTime*.7)));+ field=max(field,.14+.34*smoothstep(-.1,.4,p.y+warp*.4));+ float3 tint=mix(float3(.72,.82,1.0),spectrum(p.x*.3+p.y*.18+iTime*.07)*.8+.2,uVariant);+ return clamp(tint*field*2.2,0.0,1.0);+}+half4 main(float2 coord) {+ float cellSize=13.0*iResolution.y/1080.0;+ float2 grid=coord/cellSize;+ float2 center=(floor(grid)+.5)*cellSize/iResolution.xy;+ float3 color=asciiInput(center);+ float brightness=pow(dot(color,float3(.299,.587,.114)),.75);+ float index=clamp(floor((1.0-brightness)*16.0),0.0,15.0);+ float2 atlasCell=float2(mod(index,4.0),floor(index/4.0));+ float2 cellUV=fract(grid);+ float glyph=uMask.eval((atlasCell+cellUV)*128.0).r;+ return finish(pow(color,float3(.7))*glyph,float2(coord));+}diff --git a/examples/shader-mode/src/shaders/aurora.sksl b/examples/shader-mode/src/shaders/aurora.skslnew file mode 100644index 00000000..e51fd630--- /dev/null+++ b/examples/shader-mode/src/shaders/aurora.sksl@@ -0,0 +1,34 @@+// Fine luminous filaments sweep through a folded ribbon of light.+// Pixel-width integration attenuates line frequencies at smaller preview sizes.+half4 main(float2 coord) {+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ p=rotate(p,-.30+uVariant*.24);+ float t=iTime*.55;+ float3 color=float3(.008,.013,.025);+ for(int i=0;i<5;++i) {+ float layer=float(i);+ float center=.16*sin(p.x*3.3+t+layer*.23)+.065*sin(p.x*6.2-t*.7+layer*.4);+ center+=(layer-2.0)*.032;+ float width=.078+.037*sin(p.x*2.7+t*.6+layer*.7);+ float y=(p.y-center)/width;+ float envelope=1.0-smoothstep(.78,1.02,abs(y));+ float fold=pow(max(0.0,1.0-y*y),.65);+ float stripes=cos(y*125.0+sin(p.x*5.0+t)*9.0+layer*3.0);+ float visible=1.0-smoothstep(.5,2.0,125.0/(width*iResolution.y));+ float filaments=mix(.22,pow(.5+.5*stripes,7.0),visible);+ float edge=exp(-abs(abs(y)-.86)*40.0);+ float glint=pow(.5+.5*sin(p.x*3.0+t+layer*.6),7.0);+ float phase=smoothstep(-.7,.6,p.x+.10*sin(t));+ float3 tint=mix(float3(.06,.27,1.0),float3(.85,.10,.31),phase);+ tint=mix(tint,float3(1.0,.49,.17),smoothstep(.45,.85,phase));+ if (uVariant > .5 && uVariant < 1.5) tint=mix(float3(.04,.40,.25),float3(.6,1.0,.43),phase);+ if (uVariant > 1.5 && uVariant < 2.5) tint=mix(float3(.30,.04,.72),float3(.90,.41,.95),phase);+ if (uVariant > 2.5 && uVariant < 3.5) tint=mix(float3(.04,.65,.80),float3(.9,.95,.55),phase);+ if (uVariant > 3.5) tint=mix(float3(.95,.05,.21),float3(1.0,.69,.22),phase);+ float energy=envelope*(.07+filaments*.34+fold*.1)+edge*.6;+ color+=tint*energy*(.35+glint*.75);+ color+=float3(.68,.79,1.0)*edge*glint*.45;+ color+=tint*exp(-abs(p.y-center)*18.0)*.035;+ }+ return finish(1.0-exp(-color*1.5),coord);+}diff --git a/examples/shader-mode/src/shaders/binary-intro.sksl b/examples/shader-mode/src/shaders/binary-intro.skslnew file mode 100644index 00000000..7a7c9985--- /dev/null+++ b/examples/shader-mode/src/shaders/binary-intro.sksl@@ -0,0 +1,102 @@+// Binary grid / luminance lookup from kit/stylizePaints.ts; horizontal band+// displacement follows kit/motionBlur.ts. See README.md for the license.+// Reveal and handoff timing are measured from the reference's first 33 frames.+uniform shader uMask;++float binaryHash(float seed) {+ return hash21(float2(seed,seed*.173+7.1));+}++float binaryBand(float row,float tick,float seedScale,float frameScale,+ float gate,float offset,float amplitude,float strength) {+ float seed=row*seedScale+tick*frameScale;+ float active=step(1.0-strength*gate,binaryHash(seed));+ return (binaryHash(seed+offset)-.5)*amplitude*active;+}++float3 binaryField(float2 uv,float frame) {+ float move=smoothstep(9.0,19.0,frame);+ float2 cyanCenter=mix(float2(.18,.58),float2(.60,.80),move);+ float2 violetCenter=mix(float2(.27,-.02),float2(.72,.10),move);+ float2 cyanP=(uv-cyanCenter)/mix(float2(.37,.58),float2(.25,.47),move);+ float2 violetP=(uv-violetCenter)/float2(.48,.33);+ // Broad light patches with rectangular interruptions form the binary blocks.+ float cyan=exp(-dot(cyanP,cyanP)*1.3)*1.45;+ float violet=exp(-dot(violetP,violetP)*1.1)*1.20;+ float cyanLeft=mix(-.18,.48,move);+ float cyanRight=mix(.44,.735,move);+ float cyanTop=mix(.13,.44,move);+ float cyanMask=step(cyanLeft,uv.x)*(1.0-step(cyanRight,uv.x))*step(cyanTop,uv.y);+ float violetLeft=mix(-.20,.50,move);+ float violetMask=max(1.0-step(.10,uv.y),step(violetLeft,uv.x));+ violetMask*=1.0-step(mix(.24,.44,move),uv.y);+ float3 color=cyan*float3(.84,.97,1.0)*cyanMask;+ color+=violet*float3(.72,.52,.94)*violetMask;+ // Dim ones trace the light beyond the rectangular highlights.+ color+=cyan*float3(.11,.16,.17)+violet*float3(.075,.045,.13);+ return clamp(color,0.0,1.0);+}++float3 binaryGrid(float2 coord,float frame) {+ float2 grid=coord/30.0;+ float2 cell=floor(grid);+ float3 tint=binaryField((cell+.5)*30.0/float2(1920,1080),frame);+ float luma=dot(tint,float3(.299,.587,.114));+ float character=1.0-step(.5,pow(luma,.60)); // bright = 0, dark = 1+ float2 atlas=(float2(character,0)+fract(grid))*128.0;+ float glyph=uMask.eval(atlas).r;+ return tint*glyph;+}++float3 binaryImage(float2 coord,float frame) {+ float2 uv=coord/float2(1920,1080);+ float strength=1.0-smoothstep(4.0,11.0,frame);+ float tick=floor((frame+6.0)*.5);+ float band=floor(uv.y*12.0);+ float shift=binaryBand(band,tick,.37,7.13,.5,42.0,.25,strength);+ shift+=binaryBand(floor(uv.y*24.0),tick,.53,3.37,.7,99.0,.12,strength);+ shift+=binaryBand(floor(uv.y*72.0),tick,.71,11.71,.9,173.0,.05,strength);+ float2 sampleCoord=coord+float2(shift*1920.0,0);+ float visible=1.0;+ if(frame<2.0) {+ sampleCoord.x-=750.0;+ float line=step(.44,binaryHash(floor(uv.y*48.0)+tick*13.0));+ visible=step(.43,uv.x)*(1.0-step(.985,uv.x))*(1.0-step(.23,uv.y))*line;+ } else if(frame<10.0) {+ float coverage=mix(.47,.94,smoothstep(2.0,10.0,frame));+ visible=step(1.0-coverage,binaryHash(floor(uv.y*36.0)+tick*17.0));+ float block=binaryHash(float(floor(uv.x*7.0)+floor(uv.y*9.0)*11.0)+tick*7.0);+ visible*=step(strength*.12,block);+ }+ // RGB displacement is local to the corrupted bands, never a blurred grid.+ float split=.32+strength*1.5;+ float3 color=float3(binaryGrid(sampleCoord+float2(split,0),frame).r,+ binaryGrid(sampleCoord,frame).g,+ binaryGrid(sampleCoord-float2(split,0),frame).b);+ float scratch=step(.992,binaryHash(floor(coord.y/3.0)+tick*19.0))*strength;+ color=mix(color,float3(.035,.033,.048),scratch*.65);+ return color*visible;+}++half4 main(float2 coord) {+ float frame=floor(iTime*29.97003+.5);+ float2 sourceCoord=coord*1080.0/iResolution.y;+ float3 color=binaryImage(sourceCoord,frame);+ // Hold the grid square during the reveal. Radial shutter sampling only+ // begins at the handoff (global frame 26 / 0.8675s).+ if(frame>=20.0) {+ color=float3(0);+ float shutter=min(2.0,(frame-19.0)*.45);+ for(int i=0;i<32;++i) {+ float sampleFrame=frame+(float(i)/31.0-.5)*shutter;+ float zoom=1.0+.08*pow(max(sampleFrame-19.0,0.0),1.7);+ float2 q=(sourceCoord-float2(960,540))/zoom+float2(960,540);+ color+=binaryImage(q,19.0);+ }+ color/=32.0;+ }+ float alpha=uVariant>.5 ? 1.0-smoothstep(20.5,25.5,frame) : 1.0;+ float bloom=frame>=20.0 ? 1.0+1.8*exp(-pow((frame-22.0)/2.3,2.0)) : 1.0;+ half4 shaded=finish(color*bloom,coord);+ return half4(shaded.rgb*half(alpha),half(alpha));+}diff --git a/examples/shader-mode/src/shaders/catalog.sksl b/examples/shader-mode/src/shaders/catalog.skslnew file mode 100644index 00000000..789d2d83--- /dev/null+++ b/examples/shader-mode/src/shaders/catalog.sksl@@ -0,0 +1,59 @@+// Each invocation draws one independently moving, perspective-correct card.+// The CPU supplies its camera-space basis and culls to its projected bounds.+uniform shader uMask;+uniform float4 uAtlas;+uniform float2 uOrigin;+uniform float2 uPortal;+uniform float3 uCenter;+uniform float3 uRight;+uniform float3 uDown;+uniform float3 uCenterMotion;+uniform float3 uRightMotion;+uniform float3 uDownMotion;+uniform float uShutter;+uniform float uHero;++float cardDistance(float2 p) {+ float2 q=abs(p)-uAtlas.zw*.5+12.0;+ return length(max(q,0.0))+min(max(q.x,q.y),0.0)-12.0;+}++half4 cardSample(float2 coord,float shutter) {+ float2 screen=coord+uOrigin;+ float3 ray=float3((screen-float2(960,540))/1080.0,1.6);+ float3 center=uCenter+uCenterMotion*shutter;+ float3 right=normalize(uRight+uRightMotion*shutter);+ float3 down=normalize(uDown+uDownMotion*shutter);+ float3 normal=normalize(cross(right,down));+ float denominator=dot(ray,normal);+ if(denominator<=.001) return half4(0);+ float distance=dot(center,normal)/denominator;+ if(distance<=0.0) return half4(0);+ float3 hit=ray*distance-center;+ float2 local=float2(dot(hit,right),dot(hit,down))*768.0;+ // One screen pixel in the card's plane. No blur kernel touches the labels.+ float aa=max(.15,distance*768.0/1080.0/denominator*1.6);+ float alpha=1.0-smoothstep(-aa*.5,aa*.5,cardDistance(local));+ float2 uv=uAtlas.xy+uAtlas.zw*.5+local;+ float3 color=uMask.eval(uv).rgb;+ float facing=clamp(dot(normal,normalize(float3(-.25,-.40,1.0))),0.0,1.0);+ color*=.90+.13*facing;+ float frame=iTime*29.97003;+ if(uHero>.5 && frame>48.0) {+ float icon=1.0-smoothstep(23.5-aa*.5,23.5+aa*.5,length(uv-uPortal));+ color=mix(color,gradientAtResolution(screen,0.0,float2(1920,1080)),icon*smoothstep(48.0,49.0,frame));+ }+ // A shallow dark edge gives a tilted card visible thickness in the gaps.+ float backDistance=(dot(center,normal)+3.0/768.0)/denominator;+ float3 backHit=ray*backDistance-center-normal*(3.0/768.0);+ float2 backLocal=float2(dot(backHit,right),dot(backHit,down))*768.0;+ float edge=(1.0-smoothstep(-aa*.5,aa*.5,cardDistance(backLocal)))*(1.0-alpha);+ return half4(color*alpha+float3(.043,.044,.049)*edge,alpha+edge);+}++half4 main(float2 coord) {+ if(uShutter<.5) return cardSample(coord,.5);+ half4 color=half4(0);+ for(int i=0;i<16;++i) color+=cardSample(coord,(float(i)+.5)/16.0);+ return color/16.0;+}diff --git a/examples/shader-mode/src/shaders/common.sksl b/examples/shader-mode/src/shaders/common.skslnew file mode 100644index 00000000..9abc6feb--- /dev/null+++ b/examples/shader-mode/src/shaders/common.sksl@@ -0,0 +1,64 @@+uniform float3 iResolution;+uniform float iTime;+uniform float uProgress;+uniform float uVariant;+uniform float uBeat;++const float PI = 3.14159265;+const float TAU = 6.2831853;++// Signed distance in source pixels, stored in RG as an unsigned 16-bit value.+float maskDistance(half4 sampleColor) {+ return ((float(sampleColor.r)*65280.0+float(sampleColor.g)*255.0)/65535.0-.5)*512.0;+}++float hash21(float2 p) {+ p = fract(p * float2(123.34, 456.21));+ p += dot(p, p + 45.32);+ return fract(p.x * p.y);+}++float noise(float2 p) {+ float2 i = floor(p);+ float2 f = fract(p);+ f = f * f * (3.0 - 2.0 * f);+ return mix(mix(hash21(i), hash21(i + float2(1, 0)), f.x),+ mix(hash21(i + float2(0, 1)), hash21(i + float2(1, 1)), f.x), f.y);+}++float fbm(float2 p) {+ float sum = 0.0;+ float amplitude = 0.5;+ for (int i = 0; i < 5; ++i) {+ sum += amplitude * noise(p);+ p = float2(p.x * 1.6 - p.y * 1.2, p.x * 1.2 + p.y * 1.6) + 7.3;+ amplitude *= 0.5;+ }+ return sum;+}++float2 rotate(float2 p, float angle) {+ float c = cos(angle), s = sin(angle);+ return float2(c * p.x - s * p.y, s * p.x + c * p.y);+}++float3 spectrum(float t) {+ return 0.5 + 0.5 * cos(TAU * (t + float3(0.0, 0.33, 0.67)));+}++float capsule(float2 p, float width, float radius) {+ p.x -= clamp(p.x, -width, width);+ return length(p) - radius;+}++float line(float2 p, float2 a, float2 b, float width) {+ float2 pa = p - a, ab = b - a;+ float d = length(pa - ab * clamp(dot(pa, ab) / dot(ab, ab), 0.0, 1.0));+ return 1.0 - smoothstep(width, width + 0.07, d);+}++half4 finish(float3 color, float2 coord) {+ // Stable spatial grain dithers the dark gradients before 8-bit encoding.+ color += (hash21(coord) - 0.5) / 255.0;+ return half4(clamp(color, 0.0, 1.0), 1.0);+}diff --git a/examples/shader-mode/src/shaders/eclipse.sksl b/examples/shader-mode/src/shaders/eclipse.skslnew file mode 100644index 00000000..452a814b--- /dev/null+++ b/examples/shader-mode/src/shaders/eclipse.sksl@@ -0,0 +1,20 @@+// FlowingGradient + a backlit sphere. The composition is reconstructed from the reference.+half4 main(float2 coord) {+ float2 uv=coord/iResolution.xy;+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ float3 silk=flowingGradient(uv,18.0+iTime*.40,1.6,float3(.001,.0005,.007),+ float3(.025,.002,.075),float3(.0,.003,.008),float3(.008,.001,.024));+ float2 center=float2(.02,.77-.04*sin(iTime*.20));+ float radius=.45+.015*sin(iTime*.24);+ float d=length(p-center)-radius;+ float angle=atan(p.x-center.x,-p.y+center.y);+ float spread=.105+.085*(.5+.5*sin(angle*2.0-.4));+ float halo=exp(-max(d,0.0)/spread)*(1.0-smoothstep(-.018,.008,-d));+ float3 tint=mix(float3(.34,.045,1),float3(.46,.46,1),smoothstep(-.6,.65,p.x));+ float3 color=silk+tint*halo*.85;+ float bloom=exp(-dot((p-float2(.08,.52))*float2(.9,1.2),(p-float2(.08,.52))*float2(.9,1.2))*3.0);+ color+=tint*bloom*.12;+ float inside=1.0-smoothstep(-.005,.005,d);+ color=mix(color,silk*.68+float3(.055,.01,.15)*exp(-abs(d)*12.0),inside);+ return finish(color,coord);+}diff --git a/examples/shader-mode/src/shaders/emboss.sksl b/examples/shader-mode/src/shaders/emboss.skslnew file mode 100644index 00000000..d33a6dc3--- /dev/null+++ b/examples/shader-mode/src/shaders/emboss.sksl@@ -0,0 +1,38 @@+// Height, lighting and two shadow taps from kit/effects/emboss.ts (MIT).+uniform shader uMask;+float shapeDistance(float2 p) { return maskDistance(uMask.eval(p*iResolution.y+iResolution.xy*.5))/iResolution.y; }+float embossHeight(float d, float depth, float width) { return depth*(1.0-smoothstep(-width,width,d)); }+float3 embossShade(float2 p, float3 base, float depth) {+ float eps=.003, d=shapeDistance(p);+ float hR=embossHeight(shapeDistance(p+float2(eps,0)),depth,.003);+ float hL=embossHeight(shapeDistance(p-float2(eps,0)),depth,.003);+ float hU=embossHeight(shapeDistance(p+float2(0,eps)),depth,.003);+ float hD=embossHeight(shapeDistance(p-float2(0,eps)),depth,.003);+ float3 n=normalize(float3(-(hR-hL)/(2.0*eps),-(hU-hD)/(2.0*eps),1));+ float2 light=normalize(float2(-.6,-.8));+ float ndl=dot(n,float3(light*.819231,.573462));+ float edge=(ndl-.573462)*.8;+ float spread=abs(depth)*.06;+ float hc=embossHeight(d,depth,.003);+ float h1=embossHeight(shapeDistance(p+light*spread*.45),depth,spread);+ float h2=embossHeight(shapeDistance(p+light*spread),depth,spread);+ float shadow=smoothstep(0.0,.5,(h1-hc)/abs(depth))*.55+smoothstep(0.0,.5,(h2-hc)/abs(depth))*.45;+ float total=clamp(max(-edge,0.0)+shadow,0.0,1.0)*.44;+ return base*(1.0-total)+max(edge,0.0)*.68;+}+half4 main(float2 coord) {+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ float phase=uVariant;+ float2 shape=rotate(p,.12*sin(iTime*1.2))*(.61+.05*uProgress)+float2(-.07+.11*uProgress,.03);+ float3 bright=float3(.53,.81,.99), dark=float3(.014,.18,.44);+ if(phase>.5){bright=float3(.82,.97,.35);dark=float3(.21,.46,.055);}+ if(phase>1.5){bright=float3(1,.70,.32);dark=float3(.70,.24,.036);}+ if(phase>2.5){bright=float3(.88,.89,1.0);dark=float3(.12,.25,.86);}+ float lum=clamp(.55-p.x*.52-p.y*.16,0.0,1.0);+ float3 base=mix(dark,bright,lum);+ float d=shapeDistance(shape);+ base*=.94+.06*smoothstep(-.03,.01,d);+ float3 color=embossShade(shape,base,.30);+ color+=.016*noise3(float3(p*110.0,0));+ return finish(color,coord);+}diff --git a/examples/shader-mode/src/shaders/flow.sksl b/examples/shader-mode/src/shaders/flow.skslnew file mode 100644index 00000000..6dc0aa83--- /dev/null+++ b/examples/shader-mode/src/shaders/flow.sksl@@ -0,0 +1,33 @@+// Stateless reconstruction of ParticleFlow's flow-aligned, jittered slivers.+// The source's compute simulation cannot run as a Skia runtime fragment effect.+float fieldAngle(float2 p) {+ return noise3(float3(p*2.7,iTime*.24))*6.2+ +atan(p.y+.15,p.x-.2)*.9;+}+float energy(float2 p) {+ float bend=p.y+.12*sin(p.x*3.8+iTime*.75)+p.x*.24;+ return exp(-bend*bend*21.0);+}+half4 main(float2 coord) {+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ float3 color=float3(.013,.002,.023);+ float2 g=p*175.0, cell=floor(g);+ float brightness=0.0;+ for(int y=-1;y<=1;++y) for(int x=-1;x<=1;++x) {+ float2 c=cell+float2(x,y);+ float2 jitter=float2(hash21(c),hash21(c+31.4))-.5;+ float2 home=(c+.5+jitter*.72)/175.0;+ float angle=fieldAngle(home);+ float2 local=rotate((p-home)*175.0,-angle);+ float len=.22+.53*hash21(c+7.8);+ float d=length(float2(max(abs(local.x)-len,0.0),local.y));+ float body=1.0-smoothstep(.055,.15,d);+ brightness+=body*energy(home)*(.4+.6*hash21(c+91.3));+ }+ float e=energy(p);+ color+=float3(.55,.01,.26)*pow(e,1.2)*.46;+ float3 filament=mix(float3(.87,.015,.35),float3(1,.91,.92),pow(e,3.0));+ color+=filament*brightness*1.5;+ color+=float3(1,.48,.7)*pow(e,8.0)*.30;+ return finish(color,coord);+}diff --git a/examples/shader-mode/src/shaders/glass.sksl b/examples/shader-mode/src/shaders/glass.skslnew file mode 100644index 00000000..bebd85c2--- /dev/null+++ b/examples/shader-mode/src/shaders/glass.sksl@@ -0,0 +1,35 @@+// Adapted from kit/effects/glass.ts and FlowingGradient; see README.md for the license.+float3 glassBackdrop(float2 p) {+ float warm = uVariant;+ float3 dark = mix(float3(.001,.004,.012),float3(.012,.001,.0003),warm);+ float3 lit = mix(float3(.016,.19,.4),float3(1.0,.48,.18),warm);+ float2 uv = p/float2(iResolution.x/iResolution.y,1)+.5;+ uv.y += .07*sin(uv.x*5.0+iTime*.45);+ float3 c = flowingGradient(uv,8.0+iTime*1.3,1.8,dark,lit,dark*.2,lit*.055);+ float fold = noise3(float3(uv*float2(2,3),1.2+iTime*.14));+ return c+lit*.38*exp(-abs(fold+.1)*80.0);+}+half4 main(float2 coord) {+ float2 p = (coord-iResolution.xy*.5)/iResolution.y;+ float2 q = p-float2(.018*sin(iTime),-.07+.04*sin(iTime*.8));+ float radius = .70-.025*uProgress;+ float d = length(q)-radius;+ float z = sqrt(max(radius*radius-dot(q,q),.000001));+ // Gradient of the volumetric chord field, with the upstream slope cap.+ float2 slope = q/max(z,.001);+ slope *= min(1.0,12.0/max(length(slope),.0001));+ float strength = smoothstep(0.0,1.0,z/.11);+ float2 offset = -slope*.15*.92*strength;+ float2 lens = p+offset;+ float3 refracted = float3(glassBackdrop(lens+offset*.035).r,+ glassBackdrop(lens).g,glassBackdrop(lens-offset*.035).b);+ float3 n = normalize(float3(slope,2));+ float3 h = normalize(float3(-.5,-.866,2));+ float spec = pow(clamp(dot(n,h),0.0,1.0),32.0)*.09*strength;+ float fresnel = pow(1.0-1.0/sqrt(dot(slope,slope)+1.0),4.0)*.24;+ float edge = exp(-abs(d)*520.0);+ float3 rim = mix(float3(.48,.59,.76),spectrum(d*130.0+.2),.35);+ refracted += spec+fresnel*float3(.3,.36,.46)+edge*rim*.85;+ float3 color = mix(glassBackdrop(p),refracted,1.0-smoothstep(-.0015,.0015,d));+ return finish(color,coord);+}diff --git a/examples/shader-mode/src/shaders/gradient-shared.sksl b/examples/shader-mode/src/shaders/gradient-shared.skslnew file mode 100644index 00000000..83524b3c--- /dev/null+++ b/examples/shader-mode/src/shaders/gradient-shared.sksl@@ -0,0 +1,21 @@+// Spectral surface using the upstream cosine diffraction palette, composed as a broad lens.+float3 gradientAtResolution(float2 coord, float clock, float2 resolution) {+ float2 p=(coord-resolution*.5)/resolution.y;+ p.y+=.27;+ float angle=atan(p.y,p.x);+ float r=length(p*float2(.78,1.0));+ float angular=smoothstep(0.0,.3,r);+ float bent=r+.07*sin(angle*3.0+clock*.55)*angular+.06*noise3(float3(p*2.0,clock*.2));+ float3 band=spectrum((sin(angle)*.18+cos(angle)*.16)*angular+clock*.18+bent*.26+.13);+ band=mix(band,float3(1),.35);+ float shadow=exp(-pow((bent-.61)/.065,2.0));+ float3 deep=spectrum(sin(angle)*.25+cos(angle)*.24+clock*.15+.1)*.55;+ float3 base=mix(float3(.965,.961,.95),band,1.0-smoothstep(.63,.92,bent));+ base=mix(base,deep,shadow*.72);+ float white=exp(-dot(p-float2(.02,.03),p-float2(.02,.03))*4.5);+ base=mix(base,float3(.965,.955,1),white*.82);+ return base;+}+float3 gradientColor(float2 coord, float clock) {+ return gradientAtResolution(coord,clock,iResolution.xy);+}diff --git a/examples/shader-mode/src/shaders/gradient.sksl b/examples/shader-mode/src/shaders/gradient.skslnew file mode 100644index 00000000..cb21c2ee--- /dev/null+++ b/examples/shader-mode/src/shaders/gradient.sksl@@ -0,0 +1 @@+half4 main(float2 coord) { return finish(gradientColor(coord,iTime),coord); }diff --git a/examples/shader-mode/src/shaders/halftone.sksl b/examples/shader-mode/src/shaders/halftone.skslnew file mode 100644index 00000000..13d86b85--- /dev/null+++ b/examples/shader-mode/src/shaders/halftone.sksl@@ -0,0 +1,20 @@+uniform shader uMask;++half4 main(float2 coord) {+ float2 uv = coord / iResolution.xy;+ float2 p = rotate((coord - iResolution.xy * 0.5) / iResolution.y, iTime * 0.13);+ float2 grid = p * 105.0;+ float2 center = (floor(grid) + 0.5) / 105.0;+ float2 lookup = center * iResolution.y + iResolution.xy * .5;+ float d = maskDistance(uMask.eval(lookup));+ float mask = 1.0 - smoothstep(-2.0, 4.0, d);+ float radius = mix(0.06, 0.43, mask);+ float2 circle = fract(grid) - 0.5;+ float dotShape = 1.0 - smoothstep(radius - 0.04, radius + 0.03, length(circle));+ float shine = clamp(0.7 - circle.x - circle.y, 0.0, 1.0);+ float3 bg = float3(0.88, 0.69, 0.27);+ float3 bead = mix(float3(0.51, 0.33, 0.075), float3(1.0, 0.93, 0.60), shine);+ float3 color = mix(bg, bead, dotShape);+ color += 0.04 * sin((uv.x + uv.y) * 2800.0);+ return finish(color, coord);+}diff --git a/examples/shader-mode/src/shaders/liquid-chrome.sksl b/examples/shader-mode/src/shaders/liquid-chrome.skslnew file mode 100644index 00000000..85e23255--- /dev/null+++ b/examples/shader-mode/src/shaders/liquid-chrome.sksl@@ -0,0 +1,54 @@+// A molten silver sculpture. True geometry and studio reflections replace+// the blurred text mask; all lettering is rendered separately as SVG.+float3 moltenSpace(float3 p) {+ p.xz = rotate(p.xz, .35+iTime*.24);+ p.yz = rotate(p.yz, -.32+iTime*.11);+ return p;+}+float moltenDistance(float3 world) {+ float3 p = moltenSpace(world);+ // Broad folds, rather than noise on a perfect sphere, alter the silhouette.+ float fold = sin(p.x*3.6+p.y*.8)*sin(p.y*3.2-p.z*.9)*sin(p.z*3.4+p.x*.7);+ float folds = .10*sin(p.x*6.0+p.z*2.0)*sin(p.y*4.1-p.z*3.3);+ return (length(p)-.97+.16*fold+folds*.45)*.55;+}+float3 moltenSample(float2 p) {+ float3 background = mix(float3(.90,.91,.94),float3(.975,.972,.96),smoothstep(-.5,.45,p.y));+ float shadow = exp(-pow((p.x-.39)/.27,2.0)-pow((p.y-.345)/.04,2.0));+ background *= 1.0-.22*shadow;+ float3 ro = float3((p-float2(.39,-.015))*3.35,-3.5);+ float3 rd = float3(0,0,1);+ float travel = 1.9;+ bool hit = false;+ for (int i=0;i<84;++i) {+ float d = moltenDistance(ro+rd*travel);+ if (d<.0006) {hit=true;break;}+ travel += max(d,.0003);+ if (travel>5.0) break;+ }+ if (!hit) return background;+ float3 p3 = ro+rd*travel;+ float2 e = float2(.001,0);+ float3 n = normalize(float3(moltenDistance(p3+e.xyy)-moltenDistance(p3-e.xyy),+ moltenDistance(p3+e.yxy)-moltenDistance(p3-e.yxy),+ moltenDistance(p3+e.yyx)-moltenDistance(p3-e.yyx)));+ float3 r = reflect(rd,n);+ float3 radiance = sculptureStudio(r);+ // A narrow purple bounce links the silver to the reel's violet end card.+ radiance += float3(.18,.075,.36)*pow(max(dot(r,normalize(float3(.4,0,1))),0.0),12.0);+ float facing = max(-dot(n,rd),0.0);+ radiance *= .84+.16*pow(1.0-facing,5.0);+ return displayMetal(radiance);+}+half4 main(float2 coord) {+ // 2x2 spatial sampling keeps moving silhouettes clean at 1080p.+ float3 color=float3(0);+ for (int y=0;y<2;++y) {+ for (int x=0;x<2;++x) {+ float2 p=(coord+float2(float(x),float(y))*.5-.25-iResolution.xy*.5)/iResolution.y;+ color += moltenSample(p);+ }+ }+ color*=.25;+ return finish(color,coord);+}diff --git a/examples/shader-mode/src/shaders/material.sksl b/examples/shader-mode/src/shaders/material.skslnew file mode 100644index 00000000..4fef1e26--- /dev/null+++ b/examples/shader-mode/src/shaders/material.sksl@@ -0,0 +1,59 @@+// Chrome / CarbonFiber / bevel profiles adapted from Shader Effects Inc. (MIT).+float ringDistance(float2 p) { return abs(capsule(p,.237,.185))-.049; }+float3 carbon(float2 p, float3 n, float3 view) {+ float2 w = rotate(p,.24)*115.0;+ float2 f = fract(w)-.5, cell = floor(w);+ float parity = step(2.0,mod(cell.x-cell.y+256.0,4.0));+ float across = mix(f.y,f.x,parity);+ float2 axis = rotate(mix(float2(0,1),float2(1,0),parity),-.24);+ float tilt = sin(across*PI)*.16+sin(across*TAU*7.0)*.07;+ n = normalize(n+float3(axis*tilt,0));+ float3 l = normalize(float3(-.7,-.6,-.7)), h = normalize(l-view);+ float3 tangent = normalize(float3(axis.y,-axis.x,0));+ float3 bitangent = normalize(cross(n,tangent));+ float nh = max(dot(n,h),.001);+ float anis = exp(-(pow(dot(h,tangent)/1.4,2.0)+pow(dot(h,bitangent)/.2,2.0))/(nh*nh));+ float ao = mix(.5,1.0,smoothstep(0.0,.05,min(.5-abs(f.x),.5-abs(f.y))));+ float lum = .035+clamp(dot(n,l)*.5+.5,0.0,1.0)*.1+anis*.6;+ float3 body = mix(float3(.012,.014,.017),float3(.60,.63,.68),lum)*ao;+ float3 r = reflect(view,n);+ float grazing = 1.0-clamp(-dot(n,view),0.0,1.0);+ return body+studio5(float2(r.x,-r.y),.16,2.0,.3)*(.05+.95*pow(grazing,5.0))*1.2;+}+half4 main(float2 coord) {+ float2 p = (coord-iResolution.xy*.5)/iResolution.y;+ p /= .99+.025*sin(iTime*3.2);+ p = rotate(p,.035*sin(iTime*1.8));+ float d = ringDistance(p), eps = .0006;+ float2 grad = float2(ringDistance(p+float2(eps,0))-ringDistance(p-float2(eps,0)),+ ringDistance(p+float2(0,eps))-ringDistance(p-float2(0,eps)))/(2.0*eps);+ float3 n = bevelNormal(d,grad,.017,.65);+ n = normalize(n+float3(p*.32,0));+ float3 view = normalize(float3(p*.55,1)), r = reflect(view,n);+ r.xy = rotate(float2(r.x,-r.y),-.38+.18*sin(iTime*1.8));+ r.xz = rotate(r.xz,.22*sin(iTime*1.6));+ float3 env = chromeStudio(r,.19+smoothstep(.75,1.0,-n.z)*.2,.45,.62);+ float3 tint = uVariant > .5 && uVariant < 1.5 ? float3(1,.59,.16) : float3(1);+ float3 material = neutralTone(env*tint);+ if (uVariant > 1.5 && uVariant < 2.5) material = carbon(p,n,view);+ if (uVariant > 2.5 && uVariant < 3.5) {+ float bits = hash21(floor(p*83.0)+floor(iTime*6.0));+ material = mix(float3(.022,.008,.062),float3(.52,.29,.89),bits)*(.4+env*.6);+ material += pow(max(0.0,-n.z),12.0)*.06;+ }+ if (uVariant > 3.5 && uVariant < 4.5) {+ material = mix(float3(.90), neutralTone(env), .16 + pow(1.0+min(n.z,0.0),3.0)*.75);+ }+ if (uVariant > 4.5 && uVariant < 5.5) {+ material = float3(.22,.70,.72)*(.70+.28*max(0.0,-n.z)) + env*.045;+ }+ float shadow = exp(-abs(ringDistance(p-float2(.0,.036)))*31.0)*.09;+ float3 background = float3(.895)-shadow;+ if (uVariant > 5.5) {+ background = flowingGradient(p*.7+.5, 6.0+iTime*.6, 1.8,+ float3(.004,.012,.04),float3(.16,.65,.08),float3(.0,.12,.45),float3(.006));+ material = background*.62 + neutralTone(env)*.38;+ }+ float aa = 1.0/iResolution.y;+ return finish(mix(background,material,1.0-smoothstep(-aa,aa,d)),coord);+}diff --git a/examples/shader-mode/src/shaders/obsidian.sksl b/examples/shader-mode/src/shaders/obsidian.skslnew file mode 100644index 00000000..26100f8f--- /dev/null+++ b/examples/shader-mode/src/shaders/obsidian.sksl@@ -0,0 +1,78 @@+// One continuous twisted ribbon, photographed in an HDR strip-light studio.+// Obsidian's grazing-angle iridescence is applied to the actual 3D normal.+float3 ribbonSpace(float3 p) {+ p.xy=rotate(p.xy,-.42+iTime*.13+uVariant*.9);+ p.yz=rotate(p.yz,.46+.14*sin(iTime*.5));+ p.xz=rotate(p.xz,-.28+iTime*.17);+ return p;+}+float ribbonDistance(float3 world) {+ float3 p=ribbonSpace(world);+ float angle=atan(p.y,p.x);+ float2 q=float2(length(p.xy)-.72,p.z);+ q=rotate(q,angle*1.5+iTime*.24);+ float2 box=abs(q)-float2(.235,.070);+ return (length(max(box,0.0))+min(max(box.x,box.y),0.0)-.055)*.62;+}+float3 filmColor(float3 p, float3 n, float3 v) {+ float facing=clamp(dot(n,v),0.0,1.0);+ float angle=atan(p.y,p.x);+ float thickness=.58+.13*sin(angle*2.0+iTime*.23)+.08*p.z;+ float optical=thickness*sqrt(1.0-.45*(1.0-facing*facing));+ float phase=.5+.5*sin(optical*7.0+sin(angle)*.8+p.z*.8);+ float3 cobalt=float3(.035,.09,.32);+ float3 lavender=float3(.30,.12,.46);+ float3 petrol=float3(.06,.34,.36);+ float3 silver=float3(.48,.57,.65);+ float3 film=mix(cobalt,lavender,smoothstep(.0,.48,phase));+ film=mix(film,petrol,smoothstep(.48,.84,phase));+ film=mix(film,silver,smoothstep(.84,1.0,phase)*.65);+ if (uVariant > .5) film = mix(float3(.10,.002,.05),float3(.70,.05,.28),phase);+ return film;+}+float3 ribbonSample(float2 p) {+ float3 bg=float3(.019,.024,.037);+ bg+=float3(.022,.032,.050)*exp(-dot(p-float2(.12,-.04),p-float2(.12,-.04))*3.0);+ float3 ro=float3(0,0,-4.2), rd=normalize(float3(p*2.0,2.8));+ float travel=2.7;+ bool hit=false;+ for(int i=0;i<100;++i) {+ float d=ribbonDistance(ro+rd*travel);+ if(d<.00055) {hit=true;break;}+ travel+=max(d,.0003);+ if(travel>5.8) break;+ }+ if(!hit) return bg;+ float3 at=ro+rd*travel;+ float2 e=float2(.001,0);+ float3 n=normalize(float3(ribbonDistance(at+e.xyy)-ribbonDistance(at-e.xyy),+ ribbonDistance(at+e.yxy)-ribbonDistance(at-e.yxy),+ ribbonDistance(at+e.yyx)-ribbonDistance(at-e.yyx)));+ float3 film=filmColor(ribbonSpace(at),n,-rd);+ float fresnel=pow(1.0-max(dot(n,-rd),0.0),3.0);+ float3 reflected=sculptureStudio(reflect(rd,n));+ // Reflective colored substrate plus a clear outer coating. Bright white+ // glints describe the twist; the center faces retain visible color.+ float occlusion=0.0;+ float weight=1.0;+ for(int i=1;i<5;++i) {+ float h=float(i)*.075;+ occlusion+=max(h-ribbonDistance(at+n*h)/.62,0.0)*weight;+ weight*=.6;+ }+ float ao=clamp(1.0-occlusion*2.5,.25,1.0);+ float3 radiance=reflected*(film*.90+float3(.11))*(.48+fresnel*.8)*ao;+ radiance+=film*(.03+.05*max(dot(n,normalize(float3(-.3,-.6,-1))),0.0));+ radiance+=reflected*pow(max(dot(n,normalize(float3(-.5,-.6,-1))),0.0),35.0)*.3;+ return displayMetal(radiance);+}+half4 main(float2 coord) {+ float3 color=float3(0);+ for(int y=0;y<2;++y) {+ for(int x=0;x<2;++x) {+ float2 p=(coord+float2(float(x),float(y))*.5-.25-iResolution.xy*.5)/iResolution.y;+ color+=ribbonSample(p);+ }+ }+ return finish(color*.25,coord);+}diff --git a/examples/shader-mode/src/shaders/particles.sksl b/examples/shader-mode/src/shaders/particles.skslnew file mode 100644index 00000000..3477b536--- /dev/null+++ b/examples/shader-mode/src/shaders/particles.sksl@@ -0,0 +1,50 @@+// Deterministic SkSL reconstruction of the reference's particle relief.+// A twisted 3D shell is sampled on its surface; no baked animation or input frames.+float3 particleSpace(float3 p) {+ p.x+=.22;+ p.yz=rotate(p.yz,.32+.17*sin(iTime*.8));+ p.xz=rotate(p.xz,-.38+iTime*.2);+ return p;+}+float particleDistance(float3 p) {+ p=particleSpace(p);+ float a=atan(p.y,p.x);+ float radius=.56+.035*sin(a*3.0+iTime*.9);+ float tube=.22+.037*sin(a*2.0+iTime*.8);+ return length(float2(length(p.xy)-radius,p.z)) - tube;+}+float3 particleLayer(float3 hit,float depth) {+ float3 q=particleSpace(hit);+ float a=atan(q.y,q.x);+ float r=.56+.035*sin(a*3.0+iTime*.9);+ float b=atan(q.z,length(q.xy)-r);+ float2 uv=float2(a/TAU,b/TAU)*float2(240,84);+ uv.y+=2.7*sin(a*3.0+iTime*.4);+ float2 f=fract(uv)-.5;+ float dotShape=exp(-dot(f,f)*38.0);+ float intensity=(.65+.35*hash21(floor(uv)))*exp(-max(depth-1.15,0.0)*.8);+ float3 color=mix(float3(.28,.045,.94),float3(1,.30,.61),smoothstep(-.7,.45,-q.y-q.z*.4));+ return color*dotShape*intensity;+}+half4 main(float2 coord) {+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ float3 ro=float3(0,0,-1.9), rd=normalize(float3(p*.96,1.40));+ float travel=.6;+ float3 color=float3(.012,.003,.025);+ // Several surfaces can contribute through the gaps between particles.+ for(int i=0;i<88;++i) {+ float3 hit=ro+rd*travel;+ float d=particleDistance(hit);+ if(abs(d)<.0012) {+ color+=particleLayer(hit,travel)*2.8;+ travel+=.05;+ } else {+ travel+=max(abs(d)*.82,.0008);+ }+ if(travel>3.6) break;+ }+ // Out-of-focus spill from the rear cloud.+ float veil=exp(-abs(particleDistance(ro+rd*2.0))*14.0);+ color+=float3(.075,.007,.16)*veil;+ return finish(color,coord);+}diff --git a/examples/shader-mode/src/shaders/preview.sksl b/examples/shader-mode/src/shaders/preview.skslnew file mode 100644index 00000000..52e4cb4c--- /dev/null+++ b/examples/shader-mode/src/shaders/preview.sksl@@ -0,0 +1,36 @@+// The image is an actual native-player window recording, including controls.+uniform shader uRecording;+uniform float2 uRecordingSize;++float3 rotateWindow(float3 p, float3 angles) {+ p.yz=rotate(p.yz,angles.x);+ p.xz=rotate(p.xz,angles.y);+ p.xy=rotate(p.xy,angles.z);+ return p;+}++half4 main(float2 coord) {+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ float frame=iTime*29.97003;+ float turn=smoothstep(0.0,70.0,frame);+ // A slow turn of a rigid plane in perspective. Leave room for the nearest+ // corners so the title bar and scrub controls remain inside the frame.+ float height=mix(.86,.89,turn);+ float3 angles=mix(float3(.12,-.31,-.022),float3(-.09,.25,.022),turn);+ float3 right=rotateWindow(float3(1,0,0),angles);+ float3 down=rotateWindow(float3(0,1,0),angles);+ float3 normal=cross(right,down);+ float3 camera=float3(0,0,-2.8);+ float3 ray=float3(p,2.8);+ float distance=dot(-camera,normal)/dot(ray,normal);+ float3 hit=camera+ray*distance;+ float2 q=float2(dot(hit,right),dot(hit,down))/height;+ float aspect=uRecordingSize.x/uRecordingSize.y;+ float2 uv=q/float2(aspect,1.0)+.5;+ float2 delta=max(abs(q)-float2(aspect*.5,.5),0.0);+ float3 background=float3(.022,.023,.028)*(1.0-exp(-length(delta)*30.0)*.65);+ float edge=min(min(uv.x,1.0-uv.x)*aspect,min(uv.y,1.0-uv.y));+ float mask=smoothstep(-.5/iResolution.y,.5/iResolution.y,edge);+ float3 window=uRecording.eval(clamp(uv,0.0,1.0)*uRecordingSize).rgb;+ return finish(mix(background,window,mask),coord);+}diff --git a/examples/shader-mode/src/shaders/rays.sksl b/examples/shader-mode/src/shaders/rays.skslnew file mode 100644index 00000000..15f0d1c4--- /dev/null+++ b/examples/shader-mode/src/shaders/rays.sksl@@ -0,0 +1,8 @@+// Godrays' two noise products and seam-free radial frame; see README.md for the license.+half4 main(float2 coord) {+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ float ray=godrays(p-float2(-.34,-.38),iTime*1.4,.44,.77,.8);+ float3 tint=mix(float3(.68,.74,.91),float3(.58,.32,.90),smoothstep(1.0,2.0,iTime));+ float3 color=float3(.006,.006,.012)+ray*tint*.72;+ return finish(color,coord);+}diff --git a/examples/shader-mode/src/shaders/sculpture.sksl b/examples/shader-mode/src/shaders/sculpture.skslnew file mode 100644index 00000000..e05d1f13--- /dev/null+++ b/examples/shader-mode/src/shaders/sculpture.sksl@@ -0,0 +1,12 @@+// Photographic chrome environment adapted from Shader Effects Inc.'s Chrome.+// Long strip lights remain continuous across the folds of both sculptures.+float3 sculptureStudio(float3 ray) {+ float3 r=float3(ray.x,-ray.y,ray.z);+ float3 light=chromeStudio(r,.035,.24,1.0);+ float strip=exp(-pow((dot(r,normalize(float3(.65,.7,-.15)))-.42)/.045,2.0));+ light+=float3(1.35,1.45,1.60)*strip;+ return light;+}+float3 displayMetal(float3 linear) {+ return pow(neutralTone(max(linear,0.0)),float3(.454545));+}diff --git a/examples/shader-mode/src/shaders/source-effects.sksl b/examples/shader-mode/src/shaders/source-effects.skslnew file mode 100644index 00000000..db3972ee--- /dev/null+++ b/examples/shader-mode/src/shaders/source-effects.sksl@@ -0,0 +1,113 @@+// SkSL adaptations of Shader Effects Inc. components, MIT, copyright 2026.+// See README.md for the upstream source and license.+// Integer noise hashing is replaced with an ES2-compatible floating-point hash.++float3 gradientHash(float3 p) {+ p = fract(p * float3(.1031, .1030, .0973));+ p += dot(p, p.yxz + 33.33);+ return normalize(fract((p.xxy + p.yxx) * p.zyx) * 2.0 - 1.0 + .0001);+}+float noise3(float3 p) {+ float3 cell = floor(p), f = fract(p);+ float3 w = f*f*f*(f*(f*6.0-15.0)+10.0);+ float a = dot(gradientHash(cell), f);+ float b = dot(gradientHash(cell+float3(1,0,0)), f-float3(1,0,0));+ float c = dot(gradientHash(cell+float3(0,1,0)), f-float3(0,1,0));+ float d = dot(gradientHash(cell+float3(1,1,0)), f-float3(1,1,0));+ float e = dot(gradientHash(cell+float3(0,0,1)), f-float3(0,0,1));+ float g = dot(gradientHash(cell+float3(1,0,1)), f-float3(1,0,1));+ float h = dot(gradientHash(cell+float3(0,1,1)), f-float3(0,1,1));+ float j = dot(gradientHash(cell+float3(1,1,1)), f-float3(1,1,1));+ return 1.65*mix(mix(mix(a,b,w.x),mix(c,d,w.x),w.y),+ mix(mix(e,g,w.x),mix(h,j,w.x),w.y),w.z);+}+float3 neutralTone(float3 color) {+ float x = min(color.r, min(color.g,color.b));+ color -= x < .08 ? x-6.25*x*x : .04;+ float peak = max(color.r,max(color.g,color.b));+ if (peak < .76) return color;+ float newPeak = 1.0-.24*.24/(peak+.24-.76);+ color *= newPeak/peak;+ return mix(color,float3(newPeak),1.0-1.0/(.15*(peak-newPeak)+1.0));+}+float bevelSin(float t, float shape) {+ float machined = mix(1.0,.72*(1.0-smoothstep(.68,.92,t)),smoothstep(0.0,.14,t));+ return mix(1.0-t,machined,shape);+}+float3 bevelNormal(float sdf, float2 grad, float width, float shape) {+ float s = min(bevelSin(clamp(-sdf/width,0.0,1.0),shape),.9995);+ return float3(grad/max(length(grad),.0001)*s,-sqrt(1.0-s*s));+}+// Chrome: rectangular studio key, black flags, warm fringe, and low bounce card.+float3 chromeStudio(float3 r, float soft, float spectral, float shadows) {+ float3 warm = float3(1,.39,.08), cool = float3(.22,.39,.78);+ float horizontal = r.x/(length(r.xy)+.0001);+ float ws = .35+.65*smoothstep(-.7,.7,horizontal);+ float cs = .45+.55*smoothstep(-.7,.7,-horizontal);+ float up = smoothstep(-.65,1.0,r.y);+ float3 env = mix(mix(float3(.17,.175,.19),cool*.03+float3(.003,.003,.004),shadows),+ float3(.56,.57,.6),up*up);+ env += float3(.55,.55,.56)*smoothstep(.3,.9,r.y);+ env += cool*exp(-pow((r.y+.45)/.2,2.0))*spectral*.2*cs;+ float facing = 1.0-smoothstep(-.1,.18,r.z);+ float2 p = r.xy/max(.32-r.z,.06);+ float2 box = abs(p-float2(0,.3))-float2(.62,.28);+ float sd = length(max(box,0.0))+min(max(box.x,box.y),0.0);+ float bs = .05+soft*.4;+ env += float3(2.9,2.87,2.82)*(1.0-smoothstep(-bs*.6,bs,sd))*facing;+ env *= mix(1.0,mix(.55,.07,shadows),smoothstep(.5,.92,abs(r.x)));+ env += warm*exp(-pow(max(sd,0.0)/(.065+soft*.05),2.0))+ * smoothstep(-.06,.1,sd)*spectral*1.3*ws*facing;+ env += warm*exp(-pow((r.y+.12)/.05,2.0))*spectral*.5*ws*(1.0-facing);+ box = abs(p-float2(0,-.78))-float2(.7,.05);+ sd = length(max(box,0.0))+min(max(box.x,box.y),0.0);+ return env+float3(.5,.5,.52)*(1.0-smoothstep(-bs*.6,bs,sd))*facing;+}+float studio5(float2 p, float radius, float strength, float skyGain) {+ float sky = smoothstep(-.7,.85,p.y);+ float lum = sky*sky*skyGain;+ lum += (1.0-smoothstep(radius*.2,radius,length(p-float2(0,.55))))*1.7*strength;+ lum += (1.0-smoothstep(radius*.23,radius*1.15,length(p-float2(-.55,.18))))*1.05*strength;+ lum += (1.0-smoothstep(radius*.2,radius,length(p-float2(.55,.1))))*strength;+ lum += (1.0-smoothstep(radius*.26,radius*1.3,length(p-float2(.2,-.5))))*.7*strength;+ lum += (1.0-smoothstep(radius*.22,radius*1.1,length(p-float2(-.35,-.25))))*.85*strength;+ return lum;+}+// FlowingGradient: noise rotation, sequential shear, two warps, fold lighting.+float4 flowWarpStep(float2 p, float scale, float z, float2 a, float2 b, float reach) {+ float2 n = float2(noise3(float3(p*scale+a,z)),noise3(float3(p*scale+b,z)));+ return float4(p+n*reach,n);+}+float3 flowingGradient(float2 uv, float time, float strength,+ float3 a, float3 b, float3 c, float3 d) {+ float aspect = iResolution.x/iResolution.y;+ float t = time*.075;+ float2 q = uv-.5;+ float angle = noise3(float3(q*.8+float2(t*.4,-t*.25),1.7))*4.0*PI*strength;+ q = rotate(q/float2(1,aspect),angle)*float2(1,aspect);+ q.x += sin(q.y*5.0+t*2.0)/50.0*strength;+ q.y += sin(q.x*7.5+t*2.0)/25.0*strength;+ float4 w1 = flowWarpStep(q,2.0,t*.5+1.7,float2(5.2,1.3),float2(1.7,9.2),.25*strength);+ float4 w2 = flowWarpStep(w1.xy,1.5,t*.3+1.7,float2(8.3,2.8),float2(3.1,7.4),.2*strength);+ float zone = noise3(float3(w2.xy*1.8,t*.3+1.7));+ float hardness = pow(clamp(w1.z*.5+.5,0.0,1.0),1.5);+ float edge = mix(.5,.008,hardness);+ float t1 = smoothstep(-edge,edge,zone), t2 = smoothstep(-edge,edge,w1.w);+ float3 base = mix(mix(a,b,t1),mix(c,d,t1),t2);+ float fold = max(1.0-abs(t1*2.0-1.0),1.0-abs(t2*2.0-1.0))*hardness;+ return base*((w2.z*.5+.5)*.12+.94)*(1.0+fold*.35);+}+float rayShape(float angle, float wrapped, float blend, float radius, float freq, float intensity) {+ return mix(pow(noise(float2(wrapped*freq,radius)),intensity),+ pow(noise(float2(angle*freq,radius)),intensity),blend);+}+float godrays(float2 p, float time, float density, float intensity, float spotty) {+ float angle = atan(p.y,p.x), wrapped = mod(angle,TAU);+ float blend = smoothstep(-.15,.15,p.x);+ float r = length(p), t = time*.2, f = density*6.0, power = 4.0-3.0*intensity;+ float a = rayShape(angle,wrapped,blend,r-t*3.0,f*5.0,power)+ *rayShape(angle,wrapped,blend,r*.5*(1.0+6.5*spotty)-t*2.0,f*20.0,power);+ float b = rayShape(angle,wrapped,blend,r*1.4-t*2.5,f*4.5,power)+ *rayShape(angle,wrapped,blend,r*.7*(1.0+6.5*spotty)-t*1.8,f*15.75,power);+ return clamp(a+b*.7,0.0,1.0);+}diff --git a/examples/shader-mode/src/shaders/spectral.sksl b/examples/shader-mode/src/shaders/spectral.skslnew file mode 100644index 00000000..f4759cb6--- /dev/null+++ b/examples/shader-mode/src/shaders/spectral.sksl@@ -0,0 +1,36 @@+// A sculptural fan of interference-colored satin. A clear dark center leaves+// SVG typography readable; no raster text, binary grid or glitch overlay.+half4 main(float2 coord) {+ float2 p=(coord-iResolution.xy*.5)/iResolution.y;+ float t=iTime+uVariant*2.5;+ float2 q=p-float2(.12,.60);+ q=rotate(q,-.20+.04*sin(t*.5));+ float angle=atan(q.y,q.x);+ float radius=length(q);+ float bend=angle+.17*sin(radius*4.2-t*.6)+.085*sin(angle*4.0+t*.35);+ float phase=bend*13.0+radius*2.2-t*.35;+ float wave=sin(phase);+ float crease=pow(.5+.5*wave,30.0);+ float face=.5+.5*sin(phase-.50);+ float boundary=.22+.075*sin(angle*3.0+t*.4);+ float shape=smoothstep(boundary-.005,boundary+.005,radius);+ float3 deep=float3(.018,.020,.036);+ float3 violet=float3(.27,.10,.65);+ float3 blue=float3(.12,.36,.81);+ float3 coral=float3(.91,.29,.19);+ float palette=.5+.5*sin(bend*2.0+radius*2.7+t*.15);+ float3 tint=mix(violet,blue,smoothstep(.0,.65,palette));+ tint=mix(tint,coral,smoothstep(.65,1.0,palette));+ float thread=.5+.5*cos(phase*22.0+radius*8.0);+ float detail=1.0-smoothstep(.6,1.8,286.0/(max(radius,.25)*iResolution.y));+ float light=.025+face*.19+crease*1.85;+ light+=pow(thread,10.0)*detail*face*.12;+ float3 satin=tint*light;+ satin+=float3(.57,.69,.88)*pow(.5+.5*sin(phase+.17),90.0)*.75;+ satin*=.65+.35*smoothstep(.4,1.5,radius);+ float3 color=mix(deep,satin,shape);+ if (uVariant > 1.5) color = dot(color,float3(.299,.587,.114))*float3(.79,.95,1.0)*1.7;+ // Darken behind the title without a card or visible rectangular mask.+ color*=1.0-.7*exp(-pow(p.x/.65,4.0)-pow((p.y+.10)/.22,4.0));+ return finish(1.0-exp(-color*1.35),coord);+}diff --git a/examples/shader-mode/src/shaders/tunnel.glsl b/examples/shader-mode/src/shaders/tunnel.glslnew file mode 100644index 00000000..e2412dd5--- /dev/null+++ b/examples/shader-mode/src/shaders/tunnel.glsl@@ -0,0 +1,29 @@+// Original Shadertoy-style program. fframes supplies the built-in uniforms and+// translates mainImage to SkSL, including the bottom-left coordinate convention.+#define TAU 6.2831853+uniform float uProgress;+uniform float uVariant;+uniform float uBeat;++vec2 rotate(vec2 p, float a) {+ return vec2(cos(a) * p.x - sin(a) * p.y, sin(a) * p.x + cos(a) * p.y);+}++void mainImage(out vec4 fragColor, in vec2 fragCoord) {+ vec2 p = (fragCoord - iResolution.xy * 0.5) / iResolution.y;+ p = rotate(p, 0.3 + iTime * 0.28);+ float angle = atan(p.y, p.x);+ float sector = TAU / 7.0;+ float polygon = cos(floor(0.5 + angle / sector) * sector - angle) * length(p);+ float depth = -log(max(0.004, polygon)) * 2.2 - iTime * 2.0;+ float bands = fract(depth);+ vec3 color = mix(vec3(0.28, 0.01, 0.32), vec3(1.0, 0.73, 0.13), pow(bands, 0.55));+ color *= 0.55 + 0.45 * smoothstep(0.02, 0.16, polygon);+ vec2 q = rotate(p, -iTime * 1.2);+ float twist = q.y + 0.18 * sin(q.x * 7.0 + iTime);+ float ribbon = 1.0 - smoothstep(0.07, 0.078, abs(twist));+ ribbon *= 1.0 - smoothstep(0.42, 0.45, abs(q.x));+ float perforation = smoothstep(0.12, 0.18, length(fract(q * 125.0) - 0.5));+ color = mix(color, vec3(0.055, 0.008, 0.065) + 0.15 * (1.0 - perforation), ribbon);+ fragColor = vec4(color, 1.0);+}diff --git a/examples/shader-mode/src/titles.rs b/examples/shader-mode/src/titles.rsnew file mode 100644index 00000000..1bdd18a7--- /dev/null+++ b/examples/shader-mode/src/titles.rs@@ -0,0 +1,72 @@+use fframes::{Frame, Svgr};++fn center(text: &'static str, y: usize, size: usize, color: &'static str) -> Svgr<'static> {+ fframes::svgr!(+ <text x="960" y={y} text-anchor="middle" font-family="DM Sans" font-weight="500"+ font-size={size} letter-spacing="-1.8" fill={color}>{text}</text>+ )+}++pub(crate) fn render(name: &str, frame: &Frame) -> Svgr<'static> {+ match name {+ "Glass" => fframes::svgr!(+ <g>+ <g transform="translate(1.2 1.4)">{center("FFRAMES HAS SHADERS", 638, 68, "#ff7c51")}</g>+ <g transform="translate(-1 -1)">{center("FFRAMES HAS SHADERS", 638, 68, "#6989ff")}</g>+ {center("FFRAMES HAS SHADERS", 638, 68, "#f8f8f8")}+ </g>+ ),+ "Gradient" => center("SkSL + SHADERTOY", 576, 64, "#fcf5ff"),+ "OpenSource" => fframes::svgr!(+ <g>+ <text x="152" y="278" font-family="JetBrains Mono" font-size="26"+ letter-spacing="3" fill="#565967">"YOURS TO CREATE."</text>+ <text x="142" y="478" font-family="DM Sans" font-weight="500"+ font-size="174" letter-spacing="-7" fill="#171922">"open"</text>+ <text x="142" y="645" font-family="DM Sans" font-weight="500"+ font-size="174" letter-spacing="-7" fill="#171922">"source"</text>+ <path d="M154 722H222" stroke="#79758b" stroke-width="2" />+ <text x="152" y="785" font-family="DM Sans" font-size="32"+ fill="#565967">"Made with fframes."</text>+ </g>+ ),+ "ShaderMode" | "SpectralCut" => {+ fframes::svgr!(+ <g>+ <text x="960" y="381" text-anchor="middle" font-family="JetBrains Mono"+ font-size="27" letter-spacing="4" fill="#c9c4df">"FFRAMES"</text>+ <text x="960" y="554" text-anchor="middle" font-family="DM Sans" font-weight="500"+ font-size="152" letter-spacing="-6" fill="#f6f4ff">"shader mode"</text>+ <text x="960" y="637" text-anchor="middle" font-family="DM Sans"+ font-size="32" letter-spacing="0.5" fill="#c9c4df">"Your code. In motion."</text>+ </g>+ )+ }+ "Code" => code(frame),+ _ => Svgr::empty(),+ }+}++fn code(frame: &Frame) -> Svgr<'static> {+ let opacity = ((frame.seconds() - 0.2) / 0.3).clamp(0.0, 1.0);+ fframes::svgr!(+ <g>+ <text x="76" y="82" font-family="JetBrains Mono" font-size="23" fill="#eeecf8">"fframes / shader mode"</text>+ <text x="1844" y="82" text-anchor="end" font-family="JetBrains Mono" font-size="23" fill="#c1becd">"Skia GPU"</text>+ <g opacity={opacity}>+ <rect x="64" y="715" width="1792" height="301" rx="10" fill="#08080d" fill-opacity="0.88" stroke="#45414f" />+ <path d="M64 765H1856 M970 765V1016" stroke="#39353e" />+ <text x="95" y="748" font-family="JetBrains Mono" font-size="20" fill="#cfc9da">"light.sksl"</text>+ <text x="1006" y="748" font-family="JetBrains Mono" font-size="20" fill="#cfc9da">"src/lib.rs"</text>+ <text x="95" y="818" font-family="JetBrains Mono" font-size="25" fill="#bea4f1">"uniform float iTime;"</text>+ <text x="95" y="864" font-family="JetBrains Mono" font-size="25" fill="#e5e1ed">"half4 main(float2 coord) {"</text>+ <text x="95" y="910" font-family="JetBrains Mono" font-size="25" fill="#afd8d7">" return half4(light(coord, iTime), 1);"</text>+ <text x="95" y="956" font-family="JetBrains Mono" font-size="25" fill="#e5e1ed">"}"</text>+ <text x="1006" y="818" font-family="JetBrains Mono" font-size="25" fill="#e5e1ed">"let shader = Shader::sksl(source);"</text>+ <text x="1006" y="864" font-family="JetBrains Mono" font-size="25" fill="#afd8d7">"let layer = shader.draw(&frame, uniforms);"</text>+ <text x="1006" y="910" font-family="JetBrains Mono" font-size="25" fill="#e2c19d">{"svgr!(<image href={layer.href()}"}</text>+ <text x="1006" y="956" font-family="JetBrains Mono" font-size="25" fill="#e2c19d">{" width=\"1920\" height=\"1080\" />)"}</text>+ </g>+ </g>+ )+}diff --git a/examples/shader-mode/src/transitions.rs b/examples/shader-mode/src/transitions.rsnew file mode 100644index 00000000..88687943--- /dev/null+++ b/examples/shader-mode/src/transitions.rs@@ -0,0 +1,77 @@+//! Camera gestures and transition windows measured in source frames.++use fframes::Svgr;++fn progress(index: usize, start: usize, end: usize) -> f32 {+ ((index as f32 - start as f32) / (end - start) as f32).clamp(0.0, 1.0)+}++pub(crate) fn apply<'a>(index: usize, name: &str, composition: Svgr<'a>) -> Svgr<'a> {+ let (mut scale, mut rotation, mut skew, mut dy, mut opacity) = (1.0, 0.0, 0.0, 0.0, 1.0);+ let mut dx = 0.0;+ match name {+ "Glass" => scale = 1.0 + 3.0 * (1.0 - progress(index, 26, 35)).powi(3),+ "Halftone" => scale = 1.0 + progress(index, 253, 256).powi(3) * 1.3,+ "Flow" => scale = 1.0 + progress(index, 443, 447).powi(3) * 8.0,+ "ShaderModeEditor" => {+ scale = 0.85;+ skew = -3.0;+ rotation = -0.6;+ }+ "ShaderModeZoom" => {+ scale = 1.14;+ dx = -60.0 * (1.0 - progress(index, 586, 610));+ skew = -3.0;+ }+ "ShaderModeWide" => {+ scale = 0.86;+ skew = -2.0;+ }+ "Eclipse" => {+ let p = progress(index, 836, 849).powi(2);+ scale = 1.0 - p * 0.97;+ rotation = p * 14.0;+ dy = p * 170.0;+ opacity = progress(index, 654, 680).powi(2) * (1.0 - p);+ }+ _ => {}+ }+ let flash = if (137..148).contains(&index) {+ (-((index as f32 - 141.0) / 2.7).powi(2)).exp()+ } else if (445..450).contains(&index) {+ (-((index as f32 - 446.0) / 1.3).powi(2)).exp() * 0.45+ } else {+ 0.0+ };+ let glitch = if (608..610).contains(&index) {+ 0.18+ } else if (636..640).contains(&index) {+ progress(index + 1, 636, 640)+ } else {+ 0.0+ };+ let bars: Vec<_> = if glitch > 0.0 {+ (0..28)+ .map(|row| {+ let hash = ((row * 73 + index * 19) % 101) as f32 / 101.0;+ let y = row as f32 * 1080.0 / 28.0;+ let height = 1080.0 / 28.0 * (glitch * 1.5 - hash * 0.45).clamp(0.02, 1.0);+ fframes::svgr!(<rect x="0" y={y} width="1920" height={height} fill="#000" />)+ })+ .collect()+ } else {+ Vec::new()+ };+ fframes::svgr!(+ <g>+ <defs><clipPath id="shot-canvas"><rect width="1920" height="1080" /></clipPath></defs>+ <g clip-path="url(#shot-canvas)">+ <g opacity={opacity} transform={format!("translate({} {}) rotate({rotation}) skewX({skew}) scale({scale}) translate(-960 -540)",960.0+dx,540.0+dy)}>+ {composition}+ </g>+ {bars}+ <rect width="1920" height="1080" fill="#fffcf2" opacity={flash} />+ </g>+ </g>+ )+}diff --git a/fframes-media/src/video_decoder.rs b/fframes-media/src/video_decoder.rsindex 7d1cd6ad..0b321a6c 100644--- a/fframes-media/src/video_decoder.rs+++ b/fframes-media/src/video_decoder.rs@@ -818,10 +818,17 @@ impl FFmpegDecoder {av_frame_copy_props(self.frame_buf.latest_av_frame, self.hw_frame);}// The decoder fell back to software decoding: the frame it returned already- // holds the pixels.+ // holds the pixels. Keep a reference in the target too, since EOF may need+ // to present it again when the output frame rate exceeds the clip's rate._ if target_frame != self.frame_buf.latest_av_frame => {av_frame_unref(self.frame_buf.latest_av_frame);- av_frame_move_ref(self.frame_buf.latest_av_frame, target_frame);+ let ret = av_frame_ref(self.frame_buf.latest_av_frame, target_frame);+ if ret < 0 {+ return Err(FFramesMediaError::LibAVAudioDecodingError((+ ret,+ "Error retaining software decoded frame".to_string(),+ )));+ }}_ => (),}@@ -938,6 +945,7 @@ impl Drop for FFmpegDecoder {fn drop(&mut self) {unsafe {av_frame_free(&raw mut self.recv_frame);+ av_frame_free(&raw mut self.hw_frame);avcodec_free_context(&raw mut self.video_stream_info.codec_ctx);avformat_close_input(&raw mut self.fmt_ctx);av_packet_free(&raw mut self.pkt);diff --git a/skills/fframes-video/SKILL.md b/skills/fframes-video/SKILL.mdindex 6227f809..6bfcd857 100644--- a/skills/fframes-video/SKILL.md+++ b/skills/fframes-video/SKILL.md@@ -24,6 +24,10 @@ open the real-time preview window, and look at frames, contact sheets and loudnefiles you can read. Read `references/design.md` before designing, `references/api.md` whilewriting code and `references/audio.md` for sound.+When matching a supplied video, first follow the reference-analysis guidance in+`references/design.md`. Its cuts, pacing and motion take precedence over the design defaults+below; fast edits and intentional black frames may be part of the requested result.+## 1. InstallRust from <https://rustup.rs>, then the system libraries ffmpeg is built with:@@ -96,6 +100,25 @@ R() { cargo run --release -- "$@"; }## 3. The loop+**Do not write tests at all when using this skill.** Do not create unit, integration,+snapshot or visual-regression tests, test modules, or test harnesses. Validate the video+with `inspect`, rendered frames, contact sheets, audio checks and the native preview.++**For the GPU backend, offer the native preview before a full render.** Do not render the+whole video as a routine review step. Once the changes are ready to review:++1. Show a complete command in a copyable shell code block, using the actual project path and+ package name; do not require the user to have defined the `$R` helper. For example:+ `cd /absolute/path/to/fframes && cargo run --release -p my-video -- preview 0s`.+2. Explicitly offer to run that preview for the user. If they have already authorized+ opening or refreshing the preview, show the command and continue within that authorization.++After a requested change, set the command's start time to a specific second at or just before+the changed section, with enough lead-in to see its entrance or transition. For example,+`preview 8.5s` lets the user review a change around 9 seconds without replaying the beginning.+State which section they will see. Render the full video when the user requests the final+export; do not require another confirmation if that request is already explicit.+After every change:1. `$R timeline` lists the scenes with their frame and second ranges, and every audio track.@@ -114,10 +137,11 @@ After every change:path and spacing of a movement: easing, overshoot, stagger.6. `$R preview Intro` opens a real-time window with sound for the user to watch (spaceplay/pause, h/l seek a second, j/k step a frame, q quit). It blocks until closed, so start- it in the background or ask the user to run it. Offer it whenever the user wants to see- the video; you review with strips and frames, the user watches in the preview.-7. `$R render Intro --draft` encodes one scene at half resolution in about a second;- `$R render` writes the final `out.mp4`.+ it in the background when running it for the user. Show the command and offer to launch+ it as described above; after edits, use a specific second near the change.++When an encoded sample is needed, `$R render Intro --draft` encodes one scene at half+resolution. `$R render` writes the full video for a requested final export.Rules:- Look at the PNGs before saying anything looks good.@@ -177,9 +201,15 @@ impl Video for MyVideo<'_> {```- One scene per idea, 2-6 s each. Inside a scene `frame.seconds()` counts from the scene start.-- Animate with `frame.animate(&fframes::timeline!(at 0.2 => 0.8, animate 0.0_f32 => 1.0, Easing::EaseOut))`- and springs, `Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 }`. Leave the end- time off a spring so it settles on its own.+- Default to `frame.animate(fframes::timeline!(...))` directly in `svgr!` attributes for+ motion with fixed values. `svgr!` lifts these animations into cached statics. Define easings+ inline in the timeline, including `Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 }`;+ named easing constants are optional. Leave the end time off a spring so it settles on its own.+- For dynamic values or calls outside that optimized pattern (including `animate_loop`),+ construct timelines once on `self` and sample them by reference. Use cached+ `AnimationRuntime` values for starts that change after construction or custom/subframe+ clocks. Camera parameters and shader uniforms can use these APIs too; do not duplicate+ springs or tween interpolation. See `references/design.md` and `references/api.md`.- Markup without `{}` is cached across frames. Keep decoration literal and put animated valueson a wrapping `<g transform={..} opacity={..}>`.- `render_frame` runs for every frame on several threads: no panics, file reads or heavy work@@ -234,11 +264,13 @@ the user listen in `$R preview`.1. `$R inspect --fail-on warning` passes, or the remaining warnings are understood entrances.2. A strip of every scene looks right and key frames are checked at full size.3. `$R audio analyze` shows sensible levels.-4. `$R render -o out.mp4`, then confirm size, frame count and audio with+4. For GPU work awaiting review, show the preview command and offer to run it at the relevant+ second. When the user requests the final export, run `$R render -o out.mp4`, then confirm+ size, frame count and audio with`ffprobe -v error -show_entries stream=codec_type,width,height,nb_frames,duration out.mp4`.-Tell the user the output path, the duration, the path of a strip image and the `preview`-command to watch it.+For preview review, provide the concrete preview command, its start time and the offer to+launch it. After final export, provide the output path and duration.## Troubleshootingdiff --git a/skills/fframes-video/references/api.md b/skills/fframes-video/references/api.mdindex dff982de..bc0bb4cf 100644--- a/skills/fframes-video/references/api.md+++ b/skills/fframes-video/references/api.md@@ -71,28 +71,77 @@ impl Scene for Intro<'_> {## Animation+For motion with fixed values, put `frame.animate(fframes::timeline!(...))` directly in the+`svgr!` attribute. The SVG macro lifts the timeline into a `lazy_static` animation, resolving+its easing runtimes once. It is fine to define the easing directly in the `timeline!` block;+named constants are optional.+```rust-use fframes::{Transform, animation::Easing};+use fframes::{Color, Transform, animation::Easing};// keyframes: at START [=> END | , duration D], animate FROM => TO, EASING-let x = frame.animate(&fframes::timeline!(- at 0.0, animate -80.0_f32 => 0.0, Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 },- at 2.5 => 2.8, animate 0.0_f32 => 60.0, Easing::EaseIn,-));-let color = frame.animate(&fframes::timeline!(at 0.0 => 1.0, animate Color::hex("#fff") => Color::hex("#0ea5e9"), Easing::EaseInOut));-let t = frame.animate(&fframes::timeline!(at 0.0 => 0.5, animate Transform::scale(0.9) => Transform::scale(1.0), Easing::EaseOut));-let drift = frame.animate_loop(&fframes::timeline!(at 0.0 => 8.0, animate 0.0_f32 => 1.0, Easing::Linear));+fframes::svgr!(+ <g opacity={frame.animate(fframes::timeline!(+ at 0.0 => 0.3, animate 0.0 => 1.0, Easing::EaseOut,+ ))}+ transform={frame.animate(fframes::timeline!(+ at 0.0, animate Transform::translate(0, 60) => Transform::translate(0, 0),+ Easing::Spring { mass: 1.0, stiffness: 180.0, damping: 20.0 },+ at 2.5 => 2.8, animate Transform::translate(0, 0) => Transform::translate(0, -40),+ Easing::EaseIn,+ ))}>+ <rect x="160" y="240" width="600" height="120" rx="24"+ fill={frame.animate(fframes::timeline!(+ at 0.0 => 1.0, animate Color::hex("#fff") => Color::hex("#0ea5e9"),+ Easing::CubicBezier(0.65, 0.0, 0.35, 1.0),+ ))}+ />+ </g>+)```+- The optimizer recognizes an attribute block whose sole expression is+ `frame.animate(timeline!(...))` (also with `&timeline!(...)`). Use `f32` literals or+ imported `Color` / `Transform` constructors for the animated values; the cached timeline+ cannot capture locals such as `self`, a loop index, or a runtime start time.+- This caching belongs to `svgr!`, not `timeline!` alone. Calls outside the macro, nested+ inside other expressions, and `animate_loop` do not use this optimization. For those,+ initialize `KeyFramesAnimation` fields once in the constructor and sample with+ `frame.animate(&self.animation)` / `frame.animate_loop(&self.animation)`. Data-dependent+ staggering can also build one timeline per item in the constructor. Camera parameters,+ shader uniforms and custom projection can consume these cached animations.- Before the first keyframe the value is `from`, after the last it stays at `to`.-- Values: `f32`, `f64`, `Color`, `Transform`.-- Runtime start times (staggering, data driven): `frame.animate_runtime(AnimateRuntimeInput {- on_second, from, to, animation_runtime: &AnimationRuntime::new(duration, &easing) })`.- For springs pass a generous duration (3.0): the spring stops at its own settle time.+- Stored timelines also support `f64` and other types implementing `Animatable` with the+ required bounds; the inline optimizer supports the built-in forms listed above.+- When a start time changes after construction, use `frame.animate_runtime(AnimateRuntimeInput {+ on_second, from, to, animation_runtime: &self.runtime })`, with `self.runtime` initialized+ once using `AnimationRuntime::new(duration, &easing)`. Known item offsets belong in cached+ `timeline!` values, not per-frame runtime construction. For springs, an explicit duration+ caps the natural settle time; omit the end in `timeline!` to let the spring settle.+- For precomputed geometry, motion-blur subframes or a custom clock,+ `runtime.solve(&elapsed_seconds)` evaluates the same easing+ directly. Handle times before the start and after `get_duration()` explicitly: `solve`+ does not clamp them. Use a custom curve only when the required motion is not represented+ by the available easings.- Easing: `Linear`, `EaseIn`, `EaseOut`, `EaseInOut`, `CubicBezier(x1, y1, x2, y2)`, `Spring {..}`.- `Transform { translate_x, translate_y, scale: Scale { x, y }, rotate, .. }`,`Transform::translate(x, y)`. Scale around a point by translating by `p * (1 - s)`.+### Matching a fractional-rate reference++`Video::FPS` is currently an integer. A 30000/1001 fps source played at 30 fps has different+timing even when every frame is retained. Keep edit boundaries as integer source frames;+for source-time effects, compute `source_frame * fps_den / fps_num` and sample an easing+runtime or bind a custom shader clock. Ordinary `frame.animate` follows the frame's integer+fps; placing keyframes at `source_frame / Video::FPS` preserves their frame positions.++When exact source timing is required, retime the final export and verify every frame is+retained. For the specific 30000/1001 case, FFmpeg video options+`-vf 'settb=1/30000,setpts=N*1001' -r 30000/1001 -fps_mode cfr -video_track_timescale 30000`+give a 1001-tick frame interval. Do not combine output `-r` with `-fps_mode passthrough`.+This export step does not change the native preview's clock. See `audio.md` for preserving+the original soundtrack during muxing.+## Text```rust@@ -149,6 +198,13 @@ fframes::svgr!(<image href={layer.href()} x="0" y="0" width="1920" height="1080"- Built-in uniforms when declared: `iResolution` (the `<image>` size), `iTime`, `iTimeDelta`,`iFrame`. Pass images with `.image("iChannel0", photo)` where `photo` comes from`ctx.get_image("photo.jpg")` (an `Option`: return `Svgr::empty()` when it is missing).+- Built-in names take precedence over user uniforms: `.float("iTime", t)` does not override+ the renderer's time. Declare a different name such as `uClock` for a continuous clock+ across cuts, source time, or time remapping. `iTime` uses the `Frame` passed to `draw`.+- `coord` starts at the shader image's top-left in its own units. `iResolution` is that+ image's width and height, not the full video or a bound texture's size. For a cropped+ card/window layer, pass its origin and the full viewport size separately when projecting+ in screen space. Child shaders sample source-image pixels with `.eval(...)`.- A synced video frame is an image too, so shaders can process footage on the GPU, e.g. agreen-screen key (bind the `SyncVideoFrameInput` to a variable first, the frame borrows it):@@ -171,9 +227,14 @@ half4 main(float2 coord) {- SkSL follows GLSL ES 2: constant loop bounds, no `while`, no dynamic array indexing, nopreprocessor. `Shader::shadertoy` expands simple `#define`s; rewrite macros with argumentsand `texture()` calls.-- A compile error is logged once and the layer is skipped. Test compilation with- `fframes_skia_renderer::render::compile_shader(&shader)`.-- Only the Skia backend runs shaders; the CPU backend draws nothing in their place.+- A compile error is logged once and the layer is skipped. Validate compilation with+ `fframes_skia_renderer::render::compile_shader(&shader)` when needed; do not add a test+ suite or test module for it.+- `inspect` checks the SVG tree without executing shaders. Also compile the effects, look+ at rendered frames, and check runtime logs for unset uniforms; a clean inspection alone+ does not establish that a shader ran correctly.+- Both Skia GPU and `SkiaCpuCtx` execute runtime shaders. The separate tiny-skia CPU backend+ draws nothing in their place. Use the GPU backend for the native preview and GPU validation.## Rendering from code@@ -195,7 +256,6 @@ let (png, report) = previewer.render_inspected(frame, &mut fframes::CpuFrameRendpng.save_png("intro.png")?;let svg = previewer.svg(frame)?;let problems = previewer.inspect(frame)?.diagnostics;-fframes::snapshot::assert_frames(&mut previewer, &mut renderer, &["Intro@end"], &Default::default());```Skia: `SkiaFFramesRenderer::new_metal(&SkiaMetalCtx::new(W, H)?, SkiaPipelineConfig::default())`diff --git a/skills/fframes-video/references/design.md b/skills/fframes-video/references/design.mdindex f61d1d44..17885132 100644--- a/skills/fframes-video/references/design.md+++ b/skills/fframes-video/references/design.md@@ -4,6 +4,25 @@ Generated videos usually go wrong the same ways: too much text, everything movinlinear motion, no hierarchy, cramped margins and random colors. A simple design without thoseproblems already looks finished.+## Matching an existing video++- Probe the reference's dimensions, rational frame rate and frame count. Map cuts and short+ transitions in source frames before writing replacement scenes; duration alone does not+ establish a matching edit. Apply the pacing defaults below when designing original work.+- Extract consecutive frames around fast effects and cut boundaries. Sparse contact sheets+ can miss a sub-second reveal or conceal independent object motion. Compare reference and+ output at the same source frames, including full-size text and logo details.+- Identify which motion belongs to the camera and which belongs to individual objects.+ A single transformed wall cannot reproduce cards separating at different depths. Use+ separate object poses and perspective projection for that effect; SVG skew is a 2D transform.+- Inspect supplied shader sources and existing project assets before approximating them.+ Matching an effect also requires its scene parameters, masks, lighting, colors and timing.+ Reuse existing vector wordmarks and logo animations when requested; enlarging a small+ raster logo or glyph atlas will not preserve their sharpness.+- When inserting a UI recording, review the selected range itself: stable window bounds,+ visible controls, and the requested interaction throughout. A recording made during window+ resizing may need a later crop. Keep playback speed consistent with the intended gesture.+## Pacing- Reading time: about 3 words per second plus 1 s to notice the text. A 9 word line needs@@ -46,7 +65,13 @@ problems already looks finished.## Motion-Easing presets that look good (`use fframes::animation::Easing`):+Use **`frame.animate(fframes::timeline!(...))` directly in `svgr!` attributes** as the default+for motion with fixed values. `svgr!` lifts these inline timelines into cached statics, so+their easing runtimes are initialized once, not rebuilt every frame. Write easings such as+`Easing::Spring { ... }` or `Easing::CubicBezier(...)` directly inside the `timeline!` block.+Named easing constants are optional when reusing a preset.++Easing presets that look good (`use fframes::animation::Easing`); the values can be inlined:```rustconst SPRING_SNAPPY: Easing = Easing::Spring { mass: 1.0, stiffness: 300.0, damping: 26.0 }; // UI-like, tiny overshoot@@ -56,7 +81,7 @@ const EASE_OUT_EXPO: Easing = Easing::CubicBezier(0.16, 1.0, 0.3, 1.0); // fastconst EASE_IN_OUT: Easing = Easing::CubicBezier(0.65, 0.0, 0.35, 1.0); // camera moves, morphs```-Principles:+Not set in stone rules, but a good start for a dynamic animation:- Enter with ease-out or a spring from a short distance (40-120 px) plus opacity 0 -> 1.Exit with ease-in, faster, to a shorter distance or just opacity.- Stagger related items by 60-120 ms (lists, words, letters by 20-40 ms).@@ -67,19 +92,49 @@ Principles:### Recipes-Staggered entrance with a runtime start time:+Staggered entrance with timelines and easings inline in `svgr!`. The subtitle follows the+title by 90 ms; `svgr!` caches all four animations:```rust-fn enter(frame: &Frame, start: f32) -> (f32, f32) {- let spring = fframes::animation::AnimationRuntime::new(3.0, &SPRING_SOFT);- let fade = fframes::animation::AnimationRuntime::new(0.3, &Easing::EaseOut);- let y = frame.animate_runtime(fframes::AnimateRuntimeInput { on_second: start, from: 60.0_f32, to: 0.0, animation_runtime: &spring });- let opacity = frame.animate_runtime(fframes::AnimateRuntimeInput { on_second: start, from: 0.0_f32, to: 1.0, animation_runtime: &fade });- (y, opacity)-}-// items.iter().enumerate().map(|(i, item)| { let (y, o) = enter(&frame, 0.4 + i as f32 * 0.09); svgr!(<g opacity={o} transform={Transform::translate(0, y)}>...</g>) })+use fframes::{Transform, animation::Easing};++fframes::svgr!(+ <g>+ <g transform={frame.animate(fframes::timeline!(+ at 0.4, animate Transform::translate(0, 60) => Transform::translate(0, 0),+ Easing::Spring { mass: 1.0, stiffness: 150.0, damping: 18.0 },+ ))}+ opacity={frame.animate(fframes::timeline!(+ at 0.4 => 0.7, animate 0.0 => 1.0, Easing::EaseOut,+ ))}>+ <text x="160" y="420" font-family="DM Sans" font-size="120" fill="#fff">+ "Shader mode"+ </text>+ </g>+ <g transform={frame.animate(fframes::timeline!(+ at 0.49, animate Transform::translate(0, 40) => Transform::translate(0, 0),+ Easing::Spring { mass: 1.0, stiffness: 150.0, damping: 18.0 },+ ))}+ opacity={frame.animate(fframes::timeline!(+ at 0.49 => 0.79, animate 0.0 => 1.0, Easing::EaseOut,+ ))}>+ <text x="160" y="510" font-family="DM Sans" font-size="48" fill="#fff">+ "Made with fframes"+ </text>+ </g>+ </g>+)```+Leave the spring's end time unspecified so it can settle naturally. Keep the attribute+expression as a direct `frame.animate(timeline!(...))` call so the optimizer recognizes it.+For starts or values that depend on item data, or animations outside this pattern (including+`animate_loop`), construct timelines once on `self`. Use cached `AnimationRuntime` values+for starts that change after construction or custom/subframe clocks. See `api.md` for the+optimizer's supported forms and timing boundaries.++Some examples for inspiration:+Word-by-word title reveal: split into words, lay them out with `frame.text_width` per word(or `text-anchor="start"` with measured offsets), stagger each word 40-60 ms with a smallupward spring.