programmatic video rendering framework that is actually fast
feat(player): Add animations to the native preview GUI (#252)
Dmitriy Kovalenko9414a60997f6
diff --git a/fframes-native-player/src/app.rs b/fframes-native-player/src/app.rsindex 977369fb..cc9aee7f 100644--- a/fframes-native-player/src/app.rs+++ b/fframes-native-player/src/app.rs@@ -11,14 +11,17 @@ use winit::window::{CursorIcon, Fullscreen, Window, WindowId};use crate::controls::{Control, ControlsState, format_time};use crate::error::PlayerError;+use crate::motion::{Intent, Motion, Timing};use crate::options::PlayerBackend;use crate::presenter::Presenter;use crate::scheduler::Scheduler;use crate::studio::{Studio, StudioLayout, StudioScroll};use fframes_skia_renderer::skia_safe::Point;-/// The control bar hides after this long without pointer movement while playing.+/// The focus dock hides after this long without pointer movement while playing.const CONTROLS_IDLE_TIMEOUT: Duration = Duration::from_millis(2500);+/// Redraw interval while something of the chrome is moving.+const MOTION_FRAME: Duration = Duration::from_micros(8333);/// A frame worker finished a playback or filmstrip job.pub(crate) enum FrameReady {@@ -97,12 +100,20 @@ pub(crate) struct App<'s> {/// Toggled with `b`.controls_enabled: bool,controls_visible: bool,+ motion: Motion,+ /// Something of the chrome moved at the last check: one more frame then draws the+ /// settled values, even when that frame was late.+ was_animating: bool,needs_redraw: bool,cursor: PhysicalPosition<f64>,cursor_inside: bool,+ /// The pointer is hidden with the dock while the video plays in the focus view.+ cursor_hidden: bool,last_pointer_activity: Instant,hovered: Option<Control>,+ /// The button under a held pointer.+ pressed: Option<Control>,drag: Option<Control>,scene_press_axis: f32,/// The newest destination under the pointer while a native frame is being prepared.@@ -146,11 +157,26 @@ impl<'s> App<'s> {current: None,controls_enabled: true,controls_visible: true,+ motion: Motion::new(+ Intent {+ studio: true,+ dock: false,+ playing: config.autoplay,+ looping: config.looping,+ hovered: None,+ pressed: None,+ },+ Timing::DEFAULT,+ now,+ ),+ was_animating: false,needs_redraw: true,cursor: PhysicalPosition::default(),cursor_inside: false,+ cursor_hidden: false,last_pointer_activity: now,hovered: None,+ pressed: None,drag: None,scene_press_axis: 0.,scrub_target: None,@@ -247,6 +273,7 @@ impl<'s> App<'s> {self.controls_visible = controls_visible;self.needs_redraw = true;}+ self.follow_motion();if self.needs_redraw {self.needs_redraw = false;@@ -272,7 +299,9 @@ impl<'s> App<'s> {fn frame_ready(&mut self, event: FrameReady) {match event {FrameReady::Thumbnail(slot, image) => {- self.config.studio.set_thumbnail(slot, image);+ self.config+ .studio+ .set_thumbnail(slot, image, Instant::now());self.needs_redraw = true;}FrameReady::Failed { position, epoch }@@ -333,7 +362,7 @@ impl<'s> App<'s> {let frame = self.playhead() as i64;let second = self.config.fps as i64;match event.logical_key.as_ref() {- Key::Named(NamedKey::Space) => self.toggle_play(),+ Key::Named(NamedKey::Space) => self.toggle_play_with_flash(),Key::Named(NamedKey::Escape) | Key::Character("q") => event_loop.exit(),Key::Named(NamedKey::ArrowLeft) | Key::Character("h") => {self.seek_to_frame(frame - second);@@ -424,6 +453,61 @@ impl<'s> App<'s> {.is_some_and(|window| window.fullscreen().is_some())}+ /// What the chrome should show; the motion follows it.+ fn intent(&self) -> Intent {+ Intent {+ studio: self.studio_open,+ dock: self.controls_visible && !self.studio_open,+ playing: self.clock.is_playing(),+ looping: self.looping,+ // A slider drag keeps its thumb lit when the pointer leaves the track+ hovered: if self.drag == Some(Control::Seek) {+ Some(Control::Seek)+ } else {+ self.hovered+ },+ pressed: self.pressed,+ }+ }++ /// Points every motion of the chrome at the current state, hides the pointer with+ /// the dock, and keeps redrawing while something moves.+ fn follow_motion(&mut self) {+ let now = Instant::now();+ self.motion.follow(self.intent(), now);+ let animating = self.is_animating(now);+ if animating || self.was_animating {+ self.needs_redraw = true;+ }+ self.was_animating = animating;++ let hide_cursor = !self.studio_open && !self.controls_visible && self.cursor_inside;+ if hide_cursor != self.cursor_hidden {+ self.cursor_hidden = hide_cursor;+ if let Some(window) = &self.window {+ window.set_cursor_visible(!hide_cursor);+ }+ }+ }++ /// Whether another frame is needed: a motion of the chrome, or a thumbnail that is+ /// still fading in (its fade is kept by the studio, not by the motion).+ fn is_animating(&self, now: Instant) -> bool {+ self.motion.is_moving(now)+ || self+ .config+ .studio+ .is_fading_in(now, self.motion.thumbnail_fade())+ }++ /// Playback toggled on the video itself (a click, the space key): flash the new state+ /// in the middle of the picture, where the eye is.+ fn toggle_play_with_flash(&mut self) {+ self.toggle_play();+ self.motion.flash(self.clock.is_playing(), Instant::now());+ self.needs_redraw = true;+ }+/// Always shown while paused, while playing only after recent pointer activity.fn controls_should_be_visible(&self) -> bool {self.controls_enabled@@ -527,6 +611,7 @@ impl<'s> App<'s> {self.controls_visible = true;self.needs_redraw = true;}+ self.follow_motion();if self.needs_redraw&& let Some(window) = &self.window{@@ -538,7 +623,19 @@ impl<'s> App<'s> {let frame = self.playhead() as i64;let second = self.config.fps as i64;- match self.control_under_cursor() {+ let control = self.control_under_cursor();+ self.pressed = control.filter(|control| {+ matches!(+ control,+ Control::Back+ | Control::PlayPause+ | Control::Forward+ | Control::Loop+ | Control::Fullscreen+ | Control::Focus+ )+ });+ match control {Some(Control::Back) => self.seek_to_frame(frame - second),Some(Control::Forward) => self.seek_to_frame(frame + second),Some(control @ (Control::Seek | Control::Timeline)) => {@@ -559,13 +656,16 @@ impl<'s> App<'s> {}Some(Control::Fullscreen) => self.toggle_fullscreen(),Some(Control::Bar) => {}+ Some(Control::PlayPause) => self.toggle_play(),// Clicking the video itself toggles playback too- Some(Control::PlayPause) | None => self.toggle_play(),+ None => self.toggle_play_with_flash(),}+ self.follow_motion();self.needs_redraw = true;}fn on_pointer_released(&mut self) {+ self.pressed = None;let drag = self.drag;self.set_drag(None);if let Some(control @ Control::Scene(start)) = drag@@ -573,19 +673,20 @@ impl<'s> App<'s> {{self.step(start as i64);}+ self.follow_motion();+ if let Some(window) = &self.window {+ window.request_redraw();+ }}fn redraw(&mut self) -> Result<(), PlayerError> {self.redraw_pending = false;let controls = ControlsState {- visible: self.controls_visible,frame: self.playhead(),duration_in_frames: self.config.duration_in_frames,fps: self.config.fps,- playing: self.clock.is_playing(),- looping: self.looping,fullscreen: self.is_fullscreen(),- hovered: self.hovered,+ motion: self.motion.sample(Instant::now()),};if let Some(presenter) = self.presenter.as_mut() {@@ -594,7 +695,6 @@ impl<'s> App<'s> {&controls,&self.config.studio,&self.scroll,- self.studio_open,)?;let position = self.current.as_ref().map(|(position, _)| *position);@@ -703,6 +803,7 @@ impl ApplicationHandler<FrameReady> for App<'_> {if self.hovered.take().is_some() {self.needs_redraw = true;}+ self.follow_motion();}WindowEvent::MouseInput {state,@@ -719,10 +820,14 @@ impl ApplicationHandler<FrameReady> for App<'_> {fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {self.tick();- event_loop.set_control_flow(match self.clock.next_frame_at() {- Some(next_frame) => ControlFlow::WaitUntil(next_frame),+ let now = Instant::now();+ let next_motion_frame = self.is_animating(now).then(|| now + MOTION_FRAME);+ event_loop.set_control_flow(match (self.clock.next_frame_at(), next_motion_frame) {+ (Some(next_frame), Some(motion)) => ControlFlow::WaitUntil(next_frame.min(motion)),+ (Some(next_frame), None) => ControlFlow::WaitUntil(next_frame),+ (None, Some(motion)) => ControlFlow::WaitUntil(motion),// Paused: sleep until input or a worker delivers the requested frame.- None => ControlFlow::Wait,+ (None, None) => ControlFlow::Wait,});}}diff --git a/fframes-native-player/src/controls.rs b/fframes-native-player/src/controls.rsindex d0af0c54..252ce533 100644--- a/fframes-native-player/src/controls.rs+++ b/fframes-native-player/src/controls.rs@@ -1,13 +1,20 @@//! The playback control bar drawn over the video. It mirrors the web editor dock: a floating//! pill with quiet round buttons, one solid primary action and the system slider, using the//! dark tokens of the `ChatGPT` design system (`@openai/apps-sdk-ui`) and the system font.+//!+//! The studio draws its transport with the same buttons; the pill itself is the focus+//! view's dock. Nothing on it pops: every state is drawn from a [`Sample`] of the player's+//! [`Motion`], so the dock rises in and drops out, hover fills fade, a pressed button gives+//! and the play glyph turns into the pause glyph.use fframes_skia_renderer::skia_safe::{self, BlurStyle, Canvas, Color, Contains, Font, FontMgr, FontStyle, MaskFilter, Paint,- PaintStyle, Path, PathFillType, Point, RRect, Rect, Typeface, font_style,+ PaintCap, PaintJoin, PaintStyle, Path, PathBuilder, PathFillType, Point, RRect, Rect, Typeface,+ font_style,};use crate::icons::{self, Icon};+use crate::motion::{Easing, Sample};/// What a click on the bar does.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -18,6 +25,7 @@ pub(crate) enum Control {Seek,Timeline,Scene(usize),+ /// The focus view: the video alone, with the dock.Focus,Loop,Fullscreen,@@ -27,14 +35,13 @@ pub(crate) enum Control {/// Everything the bar shows, gathered by the app every frame.pub(crate) struct ControlsState {- pub visible: bool,pub frame: usize,pub duration_in_frames: usize,pub fps: usize,- pub playing: bool,- pub looping: bool,pub fullscreen: bool,- pub hovered: Option<Control>,+ /// Where every motion of the chrome is right now: the view, the dock, playback,+ /// looping, hover and press of every button.+ pub motion: Sample,}impl ControlsState {@@ -73,6 +80,17 @@ const TRACK_HEIGHT: f32 = 4.;const THUMB_SIZE: f32 = 14.;/// Vertical area around the track that grabs the pointer.const TRACK_HIT_HEIGHT: f32 = 24.;+/// The dock rises this far into place as it appears, and drops back out.+const BAR_RISE: f32 = 10.;+/// How much a button gives while it is held.+const PRESS_SCALE: f32 = 0.08;+/// The track thickens by this much under the pointer.+const TRACK_GROW: f32 = 1.;+/// The glyph flashed in the middle of the picture: its plate and the glyph on it.+const FLASH: Color = Color::from_argb(178, 0x1c, 0x1c, 0x1e);+const FLASH_PLATE: f32 = 88.;+const FLASH_ICON: f32 = 40.;+const FLASH_GROW: f32 = 0.25;/// Same preference order as the `--font-sans` stack of the design system.const SYSTEM_FONTS: &[&str] = &[@@ -93,11 +111,10 @@ pub(crate) struct Controls {}struct IconPaths {- play: Path,- pause: Path,back: Path,forward: Path,looping: Path,+ focus: Path,expand: Path,collapse: Path,}@@ -236,11 +253,10 @@ impl Controls {medium: typeface(font_style::Weight::MEDIUM),frame_mark,icons: IconPaths {- play: icon(icons::PLAY),- pause: icon(icons::PAUSE),back: icon(icons::BACK),forward: icon(icons::FORWARD),looping: icon(icons::LOOP),+ focus: icon(icons::FOCUS),expand: icon(icons::EXPAND),collapse: icon(icons::COLLAPSE),},@@ -256,7 +272,9 @@ impl Controls {}pub(crate) fn draw(&self, canvas: &Canvas, layout: &ControlsLayout, state: &ControlsState) {- if !state.visible {+ // The dock rises as the studio panel leaves, and is gone before it is back+ let reveal = state.motion.dock * (1. - state.motion.studio);+ if reveal <= 0. {return;}@@ -264,25 +282,27 @@ impl Controls {let mut paint = Paint::default();paint.set_anti_alias(true);+ // The dock rises into place as it fades in, and drops back out+ canvas.save();+ canvas.translate((0., (1. - reveal) * BAR_RISE * scale));+// Floating pill: elevation shadow, surface and hairline borderlet radius = layout.bar.height() / 2.;let bar = RRect::new_rect_xy(layout.bar, radius, radius);let mut shadow = paint.clone();- shadow.set_color(Color::from_argb(77, 0, 0, 0));+ shadow.set_color(fade(Color::from_argb(77, 0, 0, 0), reveal));shadow.set_mask_filter(MaskFilter::blur(BlurStyle::Normal, 8. * scale, false));canvas.draw_rrect(bar.with_offset((0., 8. * scale)), &shadow);- paint.set_color(SURFACE_ELEVATED);+ paint.set_color(fade(SURFACE_ELEVATED, reveal));canvas.draw_rrect(bar, &paint);let mut border = paint.clone();border.set_style(PaintStyle::Stroke);border.set_stroke_width(scale.max(1.));- border.set_color(HAIRLINE);+ border.set_color(fade(HAIRLINE, reveal));canvas.draw_rrect(bar, &border);- let hovered = |control| state.hovered == Some(control);-for (control, rect) in [(Control::Back, layout.back),(Control::PlayPause, layout.play),@@ -290,11 +310,11 @@ impl Controls {(Control::Loop, layout.looping),(Control::Fullscreen, layout.fullscreen),] {- self.draw_button(canvas, control, rect, state, scale);+ self.draw_button(canvas, control, rect, state, reveal, scale);}let mut text = paint.clone();- text.set_color(TEXT);+ text.set_color(fade(TEXT, reveal));draw_tabular(canvas,&format_time(state.frame, state.fps),@@ -302,7 +322,7 @@ impl Controls {&self.font(true, scale),&text,);- text.set_color(TEXT_SECONDARY);+ text.set_color(fade(TEXT_SECONDARY, reveal));draw_tabular(canvas,&format_time(state.duration_in_frames, state.fps),@@ -311,58 +331,73 @@ impl Controls {&text,);- // System slider: soft track, then the played range and the thumb ring in the brand color+ // System slider: soft track, then the played range and the thumb ring in the brand+ // color. Under the pointer the track thickens and a halo grows around the thumb.if layout.track.width() > 0. {- let track_radius = layout.track.height() / 2.;- paint.set_color(TRACK);+ let hover = state.motion.hover(Control::Seek);+ let track = layout.track.with_outset((0., hover * TRACK_GROW * scale));+ let track_radius = track.height() / 2.;+ paint.set_color(fade(TRACK, reveal));canvas.draw_rrect(- RRect::new_rect_xy(layout.track, track_radius, track_radius),+ RRect::new_rect_xy(track, track_radius, track_radius),&paint,);- let thumb_x = layout.track.left + layout.track.width() * state.progress();- let mut range = layout.track;+ let thumb_x = track.left + track.width() * state.progress();+ let mut range = track;range.right = thumb_x;- paint.set_color(BRAND);+ paint.set_color(fade(BRAND, reveal));canvas.draw_rrect(RRect::new_rect_xy(range, track_radius, track_radius),&paint,);let thumb_radius = THUMB_SIZE * scale / 2.;- let center = Point::new(thumb_x, layout.track.center_y());- if hovered(Control::Seek) {- paint.set_color(GHOST_HOVER);- canvas.draw_circle(center, thumb_radius * 1.8, &paint);+ let center = Point::new(thumb_x, track.center_y());+ if hover > 0. {+ paint.set_color(fade(GHOST_HOVER, reveal * hover));+ canvas.draw_circle(center, thumb_radius * (1. + 0.8 * hover), &paint);}- paint.set_color(BRAND);+ paint.set_color(fade(BRAND, reveal));canvas.draw_circle(center, thumb_radius, &paint);- paint.set_color(THUMB);+ paint.set_color(fade(THUMB, reveal));canvas.draw_circle(center, thumb_radius - 2. * scale, &paint);}++ canvas.restore();}+ /// A button of the dock or the studio transport, drawn from the motion in `state`:+ /// its hover fill, how far it is pressed in and, for the primary one, how far the play+ /// glyph has turned into pause. `reveal` fades the whole button with its surface.pub(crate) fn draw_button(&self,canvas: &Canvas,control: Control,rect: Rect,state: &ControlsState,+ reveal: f32,scale: f32,) {- let hovered = state.hovered == Some(control);+ let motion = &state.motion;+ let hover = motion.hover(control);+ let press = motion.press(control);let icon = match control {Control::PlayPause => {- let icon = if state.playing {- &self.icons.pause- } else {- &self.icons.play- };- return self.primary_button(canvas, rect, icon, hovered, scale);+ return self.primary_button(+ canvas,+ rect,+ motion.glyph,+ hover,+ press,+ reveal,+ scale,+ );}Control::Back => &self.icons.back,Control::Forward => &self.icons.forward,Control::Loop => &self.icons.looping,+ Control::Focus => &self.icons.focus,Control::Fullscreen => {if state.fullscreen {&self.icons.collapse@@ -372,55 +407,202 @@ impl Controls {}_ => return,};- self.ghost_button(- canvas,- rect,- icon,- hovered,- control == Control::Loop && state.looping,- scale,- );+ let on = if control == Control::Loop {+ motion.looping+ } else {+ 0.+ };+ self.ghost_button(canvas, rect, icon, hover, on, press, reveal, scale);}+ /// A quiet round button. `hover`, `on` (a toggle that is on) and `press` are each+ /// `0.0..=1.0`; the fill steps up from hover to on so the two never read alike.+ #[allow(clippy::too_many_arguments)]fn ghost_button(&self,canvas: &Canvas,rect: Rect,icon: &Path,- hovered: bool,- pressed: bool,+ hover: f32,+ on: f32,+ press: f32,+ reveal: f32,scale: f32,) {let mut paint = Paint::default();paint.set_anti_alias(true);- let background = match (hovered, pressed) {- (true, true) => Some(GHOST_ACTIVE),- (true, false) | (false, true) => Some(GHOST_HOVER),- (false, false) => None,- };- if let Some(background) = background {- paint.set_color(background);+ canvas.save();+ press_into(canvas, rect, press);++ let background = mix(+ mix(TRANSPARENT, GHOST_HOVER, hover),+ mix(GHOST_HOVER, GHOST_ACTIVE, hover),+ on,+ );+ if background.a() > 0 {+ paint.set_color(fade(background, reveal));canvas.draw_circle(rect.center(), rect.width() / 2., &paint);}- paint.set_color(if hovered || pressed {- TEXT- } else {- TEXT_SECONDARY- });+ paint.set_color(fade(mix(TEXT_SECONDARY, TEXT, hover.max(on)), reveal));draw_icon(canvas, icon, rect, scale, &paint);+ canvas.restore();}- fn primary_button(&self, canvas: &Canvas, rect: Rect, icon: &Path, hovered: bool, scale: f32) {+ /// The solid brand button with the play glyph, `glyph` turns it into pause.+ #[allow(clippy::too_many_arguments)]+ fn primary_button(+ &self,+ canvas: &Canvas,+ rect: Rect,+ glyph: f32,+ hover: f32,+ press: f32,+ reveal: f32,+ scale: f32,+ ) {let mut paint = Paint::default();paint.set_anti_alias(true);- paint.set_color(if hovered { BRAND_HOVER } else { BRAND });++ canvas.save();+ press_into(canvas, rect, press);+ paint.set_color(fade(mix(BRAND, BRAND_HOVER, hover), reveal));canvas.draw_circle(rect.center(), rect.width() / 2., &paint);- paint.set_color(TEXT_ON_BRAND);- draw_icon(canvas, icon, rect, scale, &paint);+ paint.set_color(fade(TEXT_ON_BRAND, reveal));+ draw_play_pause(canvas, rect, ICON * scale, glyph, &paint);+ canvas.restore();}++ /// Playback toggled on the video itself: its glyph on a dark plate in the middle of+ /// the picture, growing as it fades, so the eye needs no bar to see what happened.+ pub(crate) fn flash(+ &self,+ canvas: &Canvas,+ center: Point,+ scale: f32,+ progress: f32,+ playing: bool,+ ) {+ let grow = 1. + FLASH_GROW * Easing::ARRIVAL.apply(progress);+ let alpha = 1. - Easing::EASE_OUT.apply((progress - 0.2) / 0.8);+ let size = FLASH_PLATE * scale * grow;+ let plate = Rect::from_xywh(center.x - size / 2., center.y - size / 2., size, size);++ let mut paint = Paint::default();+ paint.set_anti_alias(true);+ paint.set_color(fade(FLASH, alpha));+ canvas.draw_circle(plate.center(), size / 2., &paint);+ paint.set_color(fade(TEXT, alpha));+ draw_play_pause(+ canvas,+ plate,+ FLASH_ICON * scale * grow,+ f32::from(u8::from(!playing)),+ &paint,+ );+ }+}++const TRANSPARENT: Color = Color::from_argb(0, 255, 255, 255);++/// `color` at `alpha` times its own alpha.+pub(crate) fn fade(color: Color, alpha: f32) -> Color {+ let a = (f32::from(color.a()) * alpha.clamp(0., 1.)).round() as u8;+ Color::from_argb(a, color.r(), color.g(), color.b())+}++/// `a` at `t == 0`, `b` at `t == 1`, with the alpha mixed too (a fully transparent end+/// keeps the other end's hue, so fading in never passes through black).+pub(crate) fn mix(a: Color, b: Color, t: f32) -> Color {+ let t = t.clamp(0., 1.);+ let channel = |x: u8, y: u8| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8;+ let (red_a, green_a, blue_a) = if a.a() == 0 {+ (b.r(), b.g(), b.b())+ } else {+ (a.r(), a.g(), a.b())+ };+ let (red_b, green_b, blue_b) = if b.a() == 0 {+ (a.r(), a.g(), a.b())+ } else {+ (b.r(), b.g(), b.b())+ };+ Color::from_argb(+ channel(a.a(), b.a()),+ channel(red_a, red_b),+ channel(green_a, green_b),+ channel(blue_a, blue_b),+ )+}++/// Shrinks what is drawn next around the middle of `rect` by how far it is pressed.+fn press_into(canvas: &Canvas, rect: Rect, press: f32) {+ if press <= 0. {+ return;+ }+ let s = 1. - PRESS_SCALE * press;+ let center = rect.center();+ canvas.translate((center.x, center.y));+ canvas.scale((s, s));+ canvas.translate((-center.x, -center.y));+}++/// The play triangle and the pause bars are one shape: two quads on the 24 grid whose+/// corners travel between the two, so the glyph turns into the other instead of being+/// swapped. `t` is 0 for play, 1 for pause.+fn draw_play_pause(canvas: &Canvas, rect: Rect, size: f32, t: f32, paint: &Paint) {+ const PLAY: [[f32; 2]; 8] = [+ [7., 5.9],+ [12.4, 8.92],+ [12.4, 15.08],+ [7., 18.1],+ [12.4, 8.92],+ [17.9, 11.85],+ [17.9, 12.15],+ [12.4, 15.08],+ ];+ const PAUSE: [[f32; 2]; 8] = [+ [6.5, 6.5],+ [10.5, 6.5],+ [10.5, 17.5],+ [6.5, 17.5],+ [13.5, 6.5],+ [17.5, 6.5],+ [17.5, 17.5],+ [13.5, 17.5],+ ];+ let t = t.clamp(0., 1.);+ let point = |i: usize| {+ Point::new(+ PLAY[i][0] + (PAUSE[i][0] - PLAY[i][0]) * t,+ PLAY[i][1] + (PAUSE[i][1] - PLAY[i][1]) * t,+ )+ };++ let mut path = PathBuilder::new();+ for quad in [0, 4] {+ path.move_to(point(quad));+ for i in 1..4 {+ path.line_to(point(quad + i));+ }+ path.close();+ }+ let path = path.detach();++ // Stroked and filled in one pass: the round join rounds the corners and the union+ // of both contours closes the seam between the two halves of the triangle+ let mut rounded = paint.clone();+ rounded.set_style(PaintStyle::StrokeAndFill);+ rounded.set_stroke_join(PaintJoin::Round);+ rounded.set_stroke_cap(PaintCap::Round);+ rounded.set_stroke_width(2.);++ canvas.save();+ canvas.translate((rect.center_x() - size / 2., rect.center_y() - size / 2.));+ canvas.scale((size / 24., size / 24.));+ canvas.draw_path(&path, &rounded);+ canvas.restore();}/// Icons are drawn on a 24x24 grid, centered in `rect` at the icon size.@@ -491,6 +673,7 @@ mod tests {use fframes_skia_renderer::skia_safe::{AlphaType, ColorType, ImageInfo, surfaces};use super::*;+ use crate::motion::{Intent, Motion, Timing};#[test]fn draws_the_primary_action_and_progress_in_the_brand_color() {@@ -499,14 +682,23 @@ mod tests {let layout = ControlsLayout::new(&controls, "00:30", width as f32, height as f32, 1.);let mut surface = surfaces::raster_n32_premul((width, height)).expect("raster surface");let state = ControlsState {- visible: true,frame: 450,duration_in_frames: 900,fps: 30,- playing: false,- looping: true,fullscreen: false,- hovered: None,+ motion: Motion::new(+ Intent {+ studio: false,+ dock: true,+ playing: false,+ looping: true,+ hovered: None,+ pressed: None,+ },+ Timing::DEFAULT,+ std::time::Instant::now(),+ )+ .sample(std::time::Instant::now()),};controls.draw(surface.canvas(), &layout, &state);diff --git a/fframes-native-player/src/icons.rs b/fframes-native-player/src/icons.rsindex 3bfad88c..325adecf 100644--- a/fframes-native-player/src/icons.rs+++ b/fframes-native-player/src/icons.rs@@ -1,21 +1,12 @@//! Monochrome system icons of the `ChatGPT` design system (`@openai/apps-sdk-ui`, MIT), the same-//! set the web editor uses. SVG path data on a 24x24 grid.+//! set the web editor uses. SVG path data on a 24x24 grid. The play and pause glyphs are+//! drawn by `controls::draw_play_pause`, which turns one into the other.pub(crate) struct Icon {pub path: &'static str,pub even_odd: bool,}-pub(crate) const PLAY: Icon = Icon {- path: "M7 7.638v8.724c0 1.294 1.464 2.075 2.577 1.376l6.94-4.363a1.615 1.615 0 0 0 0-2.75l-6.94-4.363C8.464 5.562 7 6.344 7 7.638Z",- even_odd: true,-};--pub(crate) const PAUSE: Icon = Icon {- path: "M6.5 7.75C6.5 7.05964 7.05964 6.5 7.75 6.5H9.25C9.94036 6.5 10.5 7.05964 10.5 7.75V16.25C10.5 16.9404 9.94036 17.5 9.25 17.5H7.75C7.05964 17.5 6.5 16.9404 6.5 16.25V7.75Z M13.5 7.75C13.5 7.05964 14.0596 6.5 14.75 6.5H16.25C16.9404 6.5 17.5 7.05964 17.5 7.75V16.25C17.5 16.9404 16.9404 17.5 16.25 17.5H14.75C14.0596 17.5 13.5 16.9404 13.5 16.25V7.75Z",- even_odd: false,-};-pub(crate) const BACK: Icon = Icon {path: "M4.47192 2.5C5.02421 2.5 5.47192 2.94772 5.47192 3.5V5.07196C7.17065 3.47759 9.45675 2.5 11.9719 2.5C17.2186 2.5 21.4719 6.75329 21.4719 12C21.4719 17.2467 17.2186 21.5 11.9719 21.5C7.10262 21.5 3.0902 17.8375 2.53692 13.1164C2.47264 12.5679 2.8652 12.0711 3.41373 12.0068C3.96226 11.9425 4.45904 12.3351 4.52333 12.8836C4.95991 16.6089 8.12901 19.5 11.9719 19.5C16.1141 19.5 19.4719 16.1421 19.4719 12C19.4719 7.85786 16.1141 4.5 11.9719 4.5C9.75153 4.5 7.75552 5.46469 6.38146 7H9.00003C9.55232 7 10 7.44772 10 8C10 8.55228 9.55232 9 9.00003 9H4.47192C3.93256 9 3.49293 8.57299 3.47265 8.03859C3.47175 8.01771 3.47151 7.99677 3.47192 7.9758V3.5C3.47192 2.94772 3.91964 2.5 4.47192 2.5Z",even_odd: false,@@ -31,6 +22,12 @@ pub(crate) const LOOP: Icon = Icon {even_odd: false,};+/// Four corner brackets: the focus view, the video alone in the window.+pub(crate) const FOCUS: Icon = Icon {+ path: "M5 4h5a1 1 0 0 1 0 2H6v4a1 1 0 0 1-2 0V5a1 1 0 0 1 1-1Z M14 4h5a1 1 0 0 1 1 1v5a1 1 0 0 1-2 0V6h-4a1 1 0 0 1 0-2Z M4 14a1 1 0 0 1 2 0v4h4a1 1 0 0 1 0 2H5a1 1 0 0 1-1-1v-5Z M19 13a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1h-5a1 1 0 0 1 0-2h4v-4a1 1 0 0 1 1-1Z",+ even_odd: false,+};+pub(crate) const EXPAND: Icon = Icon {path: "M13 4C13 3.44772 13.4477 3 14 3H20C20.5523 3 21 3.44772 21 4V10C21 10.5523 20.5523 11 20 11C19.4477 11 19 10.5523 19 10V6.41421L15.2071 10.2071C14.8166 10.5976 14.1834 10.5976 13.7929 10.2071C13.4024 9.81658 13.4024 9.18342 13.7929 8.79289L17.5858 5H14C13.4477 5 13 4.55228 13 4ZM4 13C4.55228 13 5 13.4477 5 14V17.5858L8.79289 13.7929C9.18342 13.4024 9.81658 13.4024 10.2071 13.7929C10.5976 14.1834 10.5976 14.8166 10.2071 15.2071L6.41421 19H10C10.5523 19 11 19.4477 11 20C11 20.5523 10.5523 21 10 21H4C3.44772 21 3 20.5523 3 20V14C3 13.4477 3.44772 13 4 13Z",even_odd: false,diff --git a/fframes-native-player/src/lib.rs b/fframes-native-player/src/lib.rsindex 227b4c3d..eada5a50 100644--- a/fframes-native-player/src/lib.rs+++ b/fframes-native-player/src/lib.rs@@ -20,10 +20,11 @@//! - `h`/`l` or `←`/`→`: seek one second back/forward//! - `j`/`k` or `↓`/`↑` (also `,`/`.`): step one frame back/forward, pauses//! - `g`/`G` or `Home`/`End`: first/last frame, `0`-`9`: jump to 0-90%-//! - Studio keeps playback controls above the timeline. Focus mode shows a floating-//! dock with a seek slider while paused or on pointer activity; `b` hides the dock.+//! - the studio under the video: playback controls, the time ruler, scenes, a film strip+//! and the audio lanes. The focus view (the viewfinder button, or `t`) shows the video+//! alone with a floating dock while paused or on pointer activity; `b` hides the dock.//! - click a scene to jump to its start, or drag across the timeline to scrub-//! - `[` / `]`: previous/next scene start, `t`: switch between the studio and video-only views+//! - `[` / `]`: previous/next scene start, `t`: switch between the studio and the focus view//! - scroll the audio lanes to browse overlapping clips//! - `r`: toggle looping, `f`: full screen, `q`/`Esc`: quit//!@@ -36,6 +37,7 @@ mod audio;mod controls;mod error;mod icons;+mod motion;mod options;mod presenter;mod scheduler;diff --git a/fframes-native-player/src/motion.rs b/fframes-native-player/src/motion.rsnew file mode 100644index 00000000..5309b983--- /dev/null+++ b/fframes-native-player/src/motion.rs@@ -0,0 +1,341 @@+//! The motion of the player's chrome: nothing pops. The studio and the focus view trade+//! places with the video growing or shrinking into place, the focus dock rises in and drops+//! out, hover fills and the toggle state fade, a pressed button gives under the pointer,+//! the play glyph turns into the pause glyph, a hovered scene lights up, thumbnails resolve+//! as they arrive, and a play or pause toggled on the video itself (a click, the space+//! key) flashes its glyph in the middle of the picture, where the eye is. Every value is a+//! [`Tween`] retargeted from wherever it is, so an interrupted motion never jumps.++use std::time::{Duration, Instant};++use crate::controls::Control;++/// A CSS style cubic bezier easing, `(x1, y1, x2, y2)`.+#[derive(Debug, Clone, Copy)]+pub(crate) struct Easing(f32, f32, f32, f32);++impl Easing {+ /// Travel between two states: a departure, clear travel and a soft arrival.+ pub(crate) const TRAVEL: Easing = Easing(0.45, 0., 0.1, 1.);+ /// Arrival from nowhere: fast out of the gate, a long settle.+ pub(crate) const ARRIVAL: Easing = Easing(0.25, 0.8, 0.25, 1.);+ /// UI feedback: as quick as the system.+ pub(crate) const EASE_OUT: Easing = Easing(0., 0., 0.58, 1.);++ fn bezier(p1: f32, p2: f32, t: f32) -> f32 {+ let u = 1. - t;+ 3. * u * u * t * p1 + 3. * u * t * t * p2 + t * t * t+ }++ pub(crate) fn apply(self, x: f32) -> f32 {+ if !(x > 0. && x < 1.) {+ return x.clamp(0., 1.);+ }+ // Solve x(t) = x by bisection, the curve is monotonic in x.+ let (mut low, mut high) = (0_f32, 1_f32);+ let mut t = x;+ for _ in 0..24 {+ let cx = Self::bezier(self.0, self.2, t);+ if (cx - x).abs() < 1e-4 {+ break;+ }+ if cx < x {+ low = t;+ } else {+ high = t;+ }+ t = f32::midpoint(low, high);+ }+ Self::bezier(self.1, self.3, t)+ }+}++/// A value moving from where it is to a target over a duration.+#[derive(Debug, Clone, Copy)]+pub(crate) struct Tween {+ from: f32,+ to: f32,+ start: Instant,+ duration: Duration,+ easing: Easing,+}++impl Tween {+ pub(crate) fn at(value: f32, now: Instant) -> Self {+ Self {+ from: value,+ to: value,+ start: now,+ duration: Duration::ZERO,+ easing: Easing::EASE_OUT,+ }+ }++ pub(crate) fn value(&self, now: Instant) -> f32 {+ if self.duration.is_zero() {+ return self.to;+ }+ let elapsed = now.saturating_duration_since(self.start).as_secs_f32();+ let progress = self.easing.apply(elapsed / self.duration.as_secs_f32());+ self.from + (self.to - self.from) * progress+ }++ pub(crate) fn is_moving(&self, now: Instant) -> bool {+ self.from != self.to && now.saturating_duration_since(self.start) < self.duration+ }++ /// Heads for `to`, starting from the current value so an interrupted motion continues+ /// instead of jumping. A target that is already set is left alone.+ pub(crate) fn go(&mut self, to: f32, duration: Duration, easing: Easing, now: Instant) {+ if self.to == to {+ return;+ }+ self.from = self.value(now);+ self.to = to;+ self.start = now;+ self.duration = duration;+ self.easing = easing;+ }+}++/// A glyph flashed in the middle of the frame when playback is toggled on the video.+#[derive(Debug, Clone, Copy)]+pub(crate) struct Flash {+ pub started: Instant,+ pub playing: bool,+}++impl Flash {+ pub(crate) const DURATION: Duration = Duration::from_millis(560);++ /// `0.0..1.0` through its life, `None` once it is over.+ pub(crate) fn progress(&self, now: Instant) -> Option<f32> {+ let elapsed = now.saturating_duration_since(self.started);+ (elapsed < Self::DURATION).then(|| elapsed.as_secs_f32() / Self::DURATION.as_secs_f32())+ }+}++/// What the player wants its chrome to show; the motion follows it.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct Intent {+ /// The studio (timeline) view rather than the focus view.+ pub studio: bool,+ /// The focus dock is shown.+ pub dock: bool,+ pub playing: bool,+ pub looping: bool,+ pub hovered: Option<Control>,+ pub pressed: Option<Control>,+}++/// How long each motion takes.+#[derive(Debug, Clone, Copy)]+pub(crate) struct Timing {+ /// The studio and the focus view trading places.+ pub view: Duration,+ pub reveal: Duration,+ pub conceal: Duration,+ pub hover: Duration,+ pub press: Duration,+ pub release: Duration,+ pub glyph: Duration,+ /// A thumbnail that just arrived fades in over this long.+ pub thumbnail: Duration,+ pub flash: bool,+}++impl Timing {+ pub(crate) const DEFAULT: Timing = Timing {+ view: Duration::from_millis(340),+ reveal: Duration::from_millis(260),+ conceal: Duration::from_millis(220),+ hover: Duration::from_millis(140),+ press: Duration::from_millis(80),+ release: Duration::from_millis(240),+ glyph: Duration::from_millis(240),+ thumbnail: Duration::from_millis(260),+ flash: true,+ };+}++/// The buttons that have a hover and a press of their own.+const BUTTONS: [Control; 7] = [+ Control::Back,+ Control::PlayPause,+ Control::Forward,+ Control::Seek,+ Control::Loop,+ Control::Fullscreen,+ Control::Focus,+];++fn slot(control: Control) -> Option<usize> {+ BUTTONS.iter().position(|&c| c == control)+}++pub(crate) struct Motion {+ timing: Timing,+ /// The view: 0 focus, 1 studio.+ studio: Tween,+ /// The focus dock: 0 hidden, 1 shown.+ dock: Tween,+ /// One per button: 0 at rest, 1 hovered.+ hover: [Tween; 7],+ /// One per button: 0 at rest, 1 held down.+ press: [Tween; 7],+ /// The primary glyph: 0 play, 1 pause.+ glyph: Tween,+ /// The loop toggle: 0 off, 1 on.+ looping: Tween,+ /// The scene under the pointer (by its first frame) and how lit it is.+ scene: Option<usize>,+ scene_hover: Tween,+ flash: Option<Flash>,+}++impl Motion {+ pub(crate) fn new(intent: Intent, timing: Timing, now: Instant) -> Self {+ let on = |yes: bool| Tween::at(f32::from(u8::from(yes)), now);+ let mut motion = Self {+ timing,+ studio: on(intent.studio),+ dock: on(intent.dock),+ hover: [Tween::at(0., now); 7],+ press: [Tween::at(0., now); 7],+ glyph: on(intent.playing),+ looping: on(intent.looping),+ scene: None,+ scene_hover: Tween::at(0., now),+ flash: None,+ };+ motion.follow(intent, now);+ motion+ }++ /// Retargets every value towards `intent`.+ pub(crate) fn follow(&mut self, intent: Intent, now: Instant) {+ let t = self.timing;+ let on = |yes: bool| f32::from(u8::from(yes));++ self.studio+ .go(on(intent.studio), t.view, Easing::TRAVEL, now);+ if intent.dock {+ self.dock.go(1., t.reveal, Easing::ARRIVAL, now);+ } else {+ self.dock.go(0., t.conceal, Easing::TRAVEL, now);+ }+ self.glyph+ .go(on(intent.playing), t.glyph, Easing::TRAVEL, now);+ self.looping+ .go(on(intent.looping), t.hover, Easing::EASE_OUT, now);++ for (index, control) in BUTTONS.iter().enumerate() {+ let hovered = intent.hovered == Some(*control);+ self.hover[index].go(on(hovered), t.hover, Easing::EASE_OUT, now);+ let pressed = intent.pressed == Some(*control);+ if pressed {+ self.press[index].go(1., t.press, Easing::EASE_OUT, now);+ } else {+ self.press[index].go(0., t.release, Easing::ARRIVAL, now);+ }+ }++ // A scene lights up under the pointer; moving straight onto another scene moves+ // the light, leaving fades it where it was+ if let Some(Control::Scene(start)) = intent.hovered {+ if self.scene != Some(start) {+ self.scene = Some(start);+ if self.scene_hover.value(now) > 0. {+ self.scene_hover = Tween::at(1., now);+ }+ }+ self.scene_hover.go(1., t.hover, Easing::EASE_OUT, now);+ } else {+ self.scene_hover.go(0., t.hover, Easing::EASE_OUT, now);+ }+ }++ /// How long an arriving thumbnail takes to fade in.+ pub(crate) fn thumbnail_fade(&self) -> Duration {+ self.timing.thumbnail+ }++ /// Playback was toggled somewhere other than a play button.+ pub(crate) fn flash(&mut self, playing: bool, now: Instant) {+ if self.timing.flash {+ self.flash = Some(Flash {+ started: now,+ playing,+ });+ }+ }++ /// Whether another frame is needed to finish a motion.+ pub(crate) fn is_moving(&self, now: Instant) -> bool {+ self.studio.is_moving(now)+ || self.dock.is_moving(now)+ || self.glyph.is_moving(now)+ || self.looping.is_moving(now)+ || self.scene_hover.is_moving(now)+ || self.hover.iter().any(|t| t.is_moving(now))+ || self.press.iter().any(|t| t.is_moving(now))+ || self.flash.is_some_and(|f| f.progress(now).is_some())+ }++ /// The values to draw with at `now`.+ pub(crate) fn sample(&self, now: Instant) -> Sample {+ let mut hover = [0.; 7];+ let mut press = [0.; 7];+ for index in 0..7 {+ hover[index] = self.hover[index].value(now);+ press[index] = self.press[index].value(now);+ }+ Sample {+ now,+ thumbnail_fade: self.timing.thumbnail,+ studio: self.studio.value(now),+ dock: self.dock.value(now),+ hover,+ press,+ glyph: self.glyph.value(now),+ looping: self.looping.value(now),+ scene: self+ .scene+ .map(|start| (start, self.scene_hover.value(now)))+ .filter(|(_, lit)| *lit > 0.),+ flash: self+ .flash+ .and_then(|f| f.progress(now).map(|p| (p, f.playing))),+ }+ }+}++/// A snapshot of every animated value, all in `0.0..=1.0`.+#[derive(Debug, Clone, Copy)]+pub(crate) struct Sample {+ /// When the sample was taken.+ pub now: Instant,+ /// How long an arriving thumbnail takes to fade in.+ pub thumbnail_fade: Duration,+ /// 0 focus view, 1 studio view.+ pub studio: f32,+ pub dock: f32,+ hover: [f32; 7],+ press: [f32; 7],+ pub glyph: f32,+ pub looping: f32,+ /// The hovered scene's first frame and how lit it is.+ pub scene: Option<(usize, f32)>,+ /// Progress and the state it announces, while a flash is up.+ pub flash: Option<(f32, bool)>,+}++impl Sample {+ pub(crate) fn hover(&self, control: Control) -> f32 {+ slot(control).map_or(0., |index| self.hover[index])+ }++ pub(crate) fn press(&self, control: Control) -> f32 {+ slot(control).map_or(0., |index| self.press[index])+ }+}diff --git a/fframes-native-player/src/presenter/mod.rs b/fframes-native-player/src/presenter/mod.rsindex 6cf45092..b8856972 100644--- a/fframes-native-player/src/presenter/mod.rs+++ b/fframes-native-player/src/presenter/mod.rs@@ -15,7 +15,7 @@ use fframes_skia_renderer::render::RenderCache;use fframes_skia_renderer::skia_safe::{Canvas, Color, Rect};use winit::window::Window;-use crate::controls::{Controls, ControlsLayout, ControlsState};+use crate::controls::{Control, Controls, ControlsLayout, ControlsState, mix};use crate::error::PlayerResult;use crate::options::PlayerBackend;use crate::studio::{Studio, StudioLayout, StudioScroll};@@ -127,14 +127,15 @@ impl Presenter {Ok(())}- /// Draws the current frame and overlays the controls before presenting the window.+ /// Draws the current frame and the chrome around it before presenting the window.+ /// `controls.motion.studio` places the view between focus (0) and studio (1): the+ /// video grows or shrinks into place while the panel slides off its edge.pub(crate) fn present(&mut self,frame: Option<&usvgr::Tree>,controls: &ControlsState,model: &Studio,scroll: &StudioScroll,- studio_open: bool,) -> PlayerResult<()> {let pixel_scale = self.window.scale_factor() as f32;let Self {@@ -148,76 +149,107 @@ impl Presenter {} = self;target.present(&mut |canvas| {- let view = studio_layout.as_ref().filter(|_| studio_open);- canvas.clear(matte(view));- if let Some(tree) = frame {- draw_video(canvas, tree, view, pixel_scale, *background, render_cache);+ let studio = controls.motion.studio;+ let view = studio_layout.as_ref();+ canvas.clear(mix(Color::BLACK, STUDIO_MATTE, studio));+ let size = canvas.base_layer_size();+ let window = Rect::from_iwh(size.width, size.height);+ let picture = video_rect(+ frame.map(usvgr::Tree::size),+ window,+ view,+ studio,+ pixel_scale,+ );+ if let (Some(tree), Some(picture)) = (frame, picture) {+ draw_video(canvas, tree, picture, *background, render_cache);+ }+ if let Some((progress, playing)) = controls.motion.flash {+ let center = picture.unwrap_or(window).center();+ bar.flash(canvas, center, pixel_scale, progress, playing);}- let show_bar = view.is_none();if let Some(ui) = studio_layout.as_mut() {canvas.save();canvas.scale((pixel_scale, pixel_scale));- if studio_open {+ if studio > 0. {+ let (dx, dy) = ui.closed_offset();+ canvas.save();+ canvas.translate((dx * (1. - studio), dy * (1. - studio)));ui.draw(canvas, bar, controls, model, scroll);- } else if controls.visible {- ui.draw_restore(- canvas,- bar,- controls.hovered == Some(crate::controls::Control::Focus),- );+ canvas.restore();}+ ui.draw_restore(+ canvas,+ bar,+ controls.motion.hover(Control::Focus),+ controls.motion.dock * (1. - studio),+ );canvas.restore();}- if show_bar {- bar.draw(canvas, layout, controls);- }+ bar.draw(canvas, layout, controls);})}}-fn matte(view: Option<&StudioLayout>) -> Color {- if view.is_some() {- Color::from_rgb(14, 14, 14)- } else {- Color::BLACK- }+const STUDIO_MATTE: Color = Color::from_rgb(14, 14, 14);++/// Where the video sits, in physical pixels: letterboxed into the window in the focus+/// view, into the stage of the studio, and in between while the view changes.+fn video_rect(+ video: Option<fframes::usvgr::Size>,+ window: Rect,+ view: Option<&StudioLayout>,+ studio: f32,+ pixel_scale: f32,+) -> Option<Rect> {+ let video = video?;+ let fit = |viewport: Rect, top: bool| {+ let scale = (viewport.width() / video.width()).min(viewport.height() / video.height());+ let width = video.width() * scale;+ let height = video.height() * scale;+ let x = viewport.center_x() - width / 2.;+ let y = if top {+ viewport.top+ } else {+ viewport.center_y() - height / 2.+ };+ Rect::from_xywh(x, y, width, height)+ };+ let focus = fit(window, false);+ let Some(ui) = view else {+ return Some(focus);+ };+ let stage = ui.stage;+ let staged = fit(+ Rect::from_ltrb(+ stage.left * pixel_scale,+ stage.top * pixel_scale,+ stage.right * pixel_scale,+ stage.bottom * pixel_scale,+ ),+ ui.portrait,+ );+ let lerp = |a: f32, b: f32| a + (b - a) * studio;+ Some(Rect::from_ltrb(+ lerp(focus.left, staged.left),+ lerp(focus.top, staged.top),+ lerp(focus.right, staged.right),+ lerp(focus.bottom, staged.bottom),+ ))}fn draw_video(canvas: &Canvas,tree: &usvgr::Tree,- view: Option<&StudioLayout>,- pixel_scale: f32,+ picture: Rect,background: Color,cache: &mut RenderCache,) {- let size = canvas.base_layer_size();- let viewport = view.map_or_else(- || Rect::from_iwh(size.width, size.height),- |ui| {- let stage = ui.stage;- Rect::from_ltrb(- stage.left * pixel_scale,- stage.top * pixel_scale,- stage.right * pixel_scale,- stage.bottom * pixel_scale,- )- },- );let video = tree.size();- let scale = (viewport.width() / video.width()).min(viewport.height() / video.height());- let width = video.width() * scale;- let height = video.height() * scale;- let x = viewport.center_x() - width / 2.;- let y = if view.is_some_and(|ui| ui.portrait) {- viewport.top- } else {- viewport.center_y() - height / 2.- };-+ let scale = picture.width() / video.width();canvas.save();- canvas.translate((x, y));+ canvas.translate((picture.left, picture.top));canvas.scale((scale, scale));canvas.clip_rect(Rect::from_wh(video.width(), video.height()),diff --git a/fframes-native-player/src/studio.rs b/fframes-native-player/src/studio.rsindex 49046f65..dbdca82f 100644--- a/fframes-native-player/src/studio.rs+++ b/fframes-native-player/src/studio.rs@@ -2,6 +2,7 @@//! coordinates here are logical pixels, regardless of the window's backing scale.use std::ops::Range;+use std::time::{Duration, Instant};use fframes::{AudioData, AudioTimelineSamples, AudioTimelineUnit, MediaProvider, ResolvedRenderingTimeline,@@ -12,13 +13,17 @@ use fframes_skia_renderer::skia_safe::{Point, RRect, Rect, RoundOut, SamplingOptions, surfaces,};-use crate::controls::{Control, Controls, ControlsState, draw_tabular, format_time, tabular_width};+use crate::controls::{+ Control, Controls, ControlsState, draw_tabular, fade, format_time, tabular_width,+};pub(crate) struct Studio {pub index: TimelineIndex,pub video_aspect: f32,audio: Vec<Vec<Clip>>,thumbnails: Vec<Option<Image>>,+ /// When each thumbnail arrived, so it can fade in instead of popping.+ thumbnail_arrivals: Vec<Option<Instant>>,thumbnail_revision: u64,}@@ -67,15 +72,46 @@ impl Studio {video_aspect,audio: pack_clips(clips),thumbnails: vec![None; thumbnail_count],+ thumbnail_arrivals: vec![None; thumbnail_count],thumbnail_revision: 0,}}- pub fn set_thumbnail(&mut self, slot: usize, image: Image) {+ pub fn set_thumbnail(&mut self, slot: usize, image: Image, now: Instant) {self.thumbnails[slot] = Some(image);+ self.thumbnail_arrivals[slot] = Some(now);self.thumbnail_revision += 1;}+ /// Whether a thumbnail that arrived less than `fade` ago is still fading in.+ pub fn is_fading_in(&self, now: Instant, fade: Duration) -> bool {+ !fade.is_zero()+ && self+ .thumbnail_arrivals+ .iter()+ .flatten()+ .any(|arrival| now.saturating_duration_since(*arrival) < fade)+ }++ /// How far each thumbnail has faded in at `now`, `1.0` once it is fully there.+ fn thumbnail_presence(&self, state: &ControlsState) -> impl Iterator<Item = (usize, f32)> {+ let motion = &state.motion;+ self.thumbnail_arrivals+ .iter()+ .enumerate()+ .filter_map(move |(slot, arrival)| {+ let arrival = (*arrival)?;+ let elapsed = motion.now.saturating_duration_since(arrival);+ if motion.thumbnail_fade.is_zero() || elapsed >= motion.thumbnail_fade {+ return None;+ }+ Some((+ slot,+ elapsed.as_secs_f32() / motion.thumbnail_fade.as_secs_f32(),+ ))+ })+ }+pub fn adjacent_scene(&self, frame: usize, next: bool) -> Option<usize> {let starts = self.index@@ -188,6 +224,7 @@ pub(crate) struct StudioScroll {pub(crate) struct StudioLayout {pub stage: Rect,timeline: Rect,+ /// The pill of the focus view that brings the studio back.restore: Rect,transport: Rect,pub portrait: bool,@@ -199,6 +236,9 @@ pub(crate) struct StudioLayout {struct TimelineCache {image: Image,bounds: IRect,+ /// Where the canvas was: the panel moves while the views change, and the cache is+ /// made again at each position (a few frames, the studio draws in about a millisecond).+ translation: (f32, f32),frames: Range<usize>,thumbnail_revision: u64,audio_scroll: usize,@@ -428,13 +468,12 @@ impl StudioLayout {let size = if narrow { 26. } else { 32. };let play_size = if narrow { 30. } else { 36. };let gap = if narrow { 2. } else { 5. };- let focus_width = if narrow { 43. } else { 58. };let margin = if narrow { 8. } else { MARGIN };let mid = width / 2.;let y = self.transport.center_y();let button = |x, w, h| Rect::from_xywh(x, y - h / 2., w, h);let play = button(mid - play_size / 2., play_size, play_size);- let focus = button(width - margin - focus_width, focus_width, size);+ let focus = button(width - margin - size, size, size);let full = button(focus.left - gap - size, size, size);[(Control::Back, button(play.left - gap - size, size, size)),@@ -446,6 +485,16 @@ impl StudioLayout {]}+ /// The translation that moves the whole panel off its edge of the window, so the+ /// studio can slide away as the focus view takes over.+ pub fn closed_offset(&self) -> (f32, f32) {+ if self.portrait {+ (-self.timeline.right, 0.)+ } else {+ (0., self.timeline.bottom - self.timeline.top)+ }+ }+pub fn time_axis(&self, point: Point) -> f32 {if self.portrait { point.y } else { point.x }}@@ -505,15 +554,24 @@ impl StudioLayout {self.restore.contains(point)}- pub fn draw_restore(&self, canvas: &Canvas, controls: &Controls, hovered: bool) {+ /// The pill that brings the studio back, shown with the focus dock: `reveal` fades it+ /// with the dock, `hover` lights it.+ pub fn draw_restore(&self, canvas: &Canvas, controls: &Controls, hover: f32, reveal: f32) {+ if reveal <= 0. {+ return;+ }let ui = Ink::new(canvas, controls);- ui.round(self.restore, if hovered { LINE } else { SURFACE }, 7.);+ ui.round(+ self.restore,+ fade(crate::controls::mix(SURFACE, LINE, hover), reveal),+ 7.,+ );ui.text("Studio · T",self.restore.left + 13.,30.,13.,- TEXT,+ fade(TEXT, reveal),true,);}@@ -528,10 +586,102 @@ impl StudioLayout {) {let ui = Ink::new(canvas, controls);self.draw_cached_timeline(&ui, state, model, scroll);+ self.draw_arriving_thumbnails(&ui, state, model);+ self.draw_scene_hover(&ui, state, model);self.draw_transport(&ui, controls, state);self.draw_playhead(&ui, state);}+ /// The rectangle of every thumbnail slot and the rounded strip that clips them.+ fn thumbnail_slots(&self, count: usize) -> Option<(RRect, Vec<Rect>)> {+ if count == 0 {+ return None;+ }+ let track = self.tracks();+ if self.portrait {+ let film = self.portrait_columns().0;+ let h = film.height() / count as f32;+ let slots = (0..count)+ .map(|i| Rect::from_xywh(film.left, film.top + i as f32 * h, film.width(), h))+ .collect();+ return Some((RRect::new_rect_xy(film, 4., 4.), slots));+ }+ if self.film_height <= 0. {+ return None;+ }+ let strip_top = track.top + RULER + SCENE_HEIGHT;+ let strip = Rect::from_ltrb(+ track.left,+ strip_top,+ track.right,+ strip_top + self.film_height,+ );+ let w = strip.width() / count as f32;+ let slots = (0..count)+ .map(|i| Rect::from_xywh(track.left + i as f32 * w, strip.top, w, self.film_height))+ .collect();+ Some((RRect::new_rect_xy(strip, 5., 5.), slots))+ }++ /// A thumbnail that just arrived is still covered by the strip's own color, which+ /// clears over the fade: the picture resolves instead of popping in.+ fn draw_arriving_thumbnails(&self, ui: &Ink<'_>, state: &ControlsState, model: &Studio) {+ let arriving: Vec<(usize, f32)> = model.thumbnail_presence(state).collect();+ if arriving.is_empty() {+ return;+ }+ let Some((clip, slots)) = self.thumbnail_slots(model.thumbnails.len()) else {+ return;+ };+ let canvas = ui.canvas;+ canvas.save();+ canvas.clip_rrect(clip, None, true);+ for (slot, presence) in arriving {+ ui.fill(slots[slot], fade(CANVAS, 1. - presence));+ }+ canvas.restore();+ }++ /// The scene under the pointer is lit a step above its band, around the film strip.+ fn draw_scene_hover(&self, ui: &Ink<'_>, state: &ControlsState, model: &Studio) {+ let Some((start, lit)) = state.motion.scene else {+ return;+ };+ let Some(scene) = model+ .index+ .scenes+ .iter()+ .find(|scene| scene.frames.start == start)+ else {+ return;+ };+ let duration = state.duration_in_frames;+ let color = fade(+ SCENE_COLORS[scene.index % SCENE_COLORS.len()].with_a(26),+ lit,+ );+ let track = self.tracks();+ if self.portrait {+ let scenes = self.portrait_columns().1;+ let top = self.frame_position(scene.frames.start, duration);+ let bottom = self.frame_position(scene.frames.end, duration);+ ui.fill(+ Rect::from_ltrb(scenes.left, top, scenes.right, (bottom - 1.).max(top)),+ color,+ );+ return;+ }+ let left = self.frame_position(scene.frames.start, duration);+ let right = self.frame_position(scene.frames.end, duration);+ let scene_top = track.top + RULER;+ let strip_top = scene_top + SCENE_HEIGHT;+ ui.fill(Rect::from_ltrb(left, scene_top, right, strip_top), color);+ ui.fill(+ Rect::from_ltrb(left, strip_top + self.film_height, right, track.bottom),+ color,+ );+ }+fn draw_transport(&self, ui: &Ink<'_>, controls: &Controls, state: &ControlsState) {let canvas = ui.canvas;ui.fill(self.transport, SURFACE);@@ -606,21 +756,7 @@ impl StudioLayout {);for (control, rect) in buttons {- if control == Control::Focus {- if state.hovered == Some(control) {- ui.round(rect, LINE, 6.);- }- let font = ui.font.with_size(13.).unwrap();- let x = rect.center_x() - font.measure_str("Focus", None).0 / 2.;- canvas.draw_str(- "Focus",- (x, center + font.metrics().1.cap_height / 2.),- &font,- &Ink::paint(TEXT),- );- } else {- controls.draw_button(canvas, control, rect, state, 1.);- }+ controls.draw_button(canvas, control, rect, state, 1., 1.);}ui.fill(Rect::from_xywh(0., self.transport.bottom - 1., self.transport.width(), 1.),@@ -638,8 +774,10 @@ impl StudioLayout {let canvas = ui.canvas;let matrix = canvas.local_to_device_as_3x3();let scale = (matrix.scale_x(), matrix.scale_y());+ let translation = (matrix.translate_x(), matrix.translate_y());let valid = self.timeline_cache.as_ref().is_some_and(|cache| {cache.frames.contains(&state.frame)+ && cache.translation == translation&& cache.thumbnail_revision == model.thumbnail_revision&& cache.audio_scroll == scroll.audio&& cache.scale == scale@@ -677,6 +815,7 @@ impl StudioLayout {TimelineCache {image: surface.image_snapshot(),bounds,+ translation,frames,thumbnail_revision: model.thumbnail_revision,audio_scroll: scroll.audio,@@ -977,6 +1116,7 @@ mod tests {},audio: vec![],thumbnails: vec![],+ thumbnail_arrivals: vec![],thumbnail_revision: 0,}}@@ -996,6 +1136,7 @@ mod tests {let controls = Controls::new();let mut model = studio();model.thumbnails = vec![None];+ model.thumbnail_arrivals = vec![None];model.audio = (0..4).map(|i| {vec![Clip {@@ -1007,14 +1148,23 @@ mod tests {.collect();let mut scroll = StudioScroll::default();let mut state = ControlsState {- visible: true,frame: 0,duration_in_frames: 100,fps: 30,- playing: true,- looping: true,fullscreen: false,- hovered: None,+ motion: crate::motion::Motion::new(+ crate::motion::Intent {+ studio: true,+ dock: false,+ playing: true,+ looping: true,+ hovered: None,+ pressed: None,+ },+ crate::motion::Timing::DEFAULT,+ Instant::now(),+ )+ .sample(Instant::now()),};let draw = |layout: &mut StudioLayout,state: &ControlsState,@@ -1064,7 +1214,10 @@ mod tests {thumbnail.canvas().clear(Color::RED);for updated_thumbnail in [false, true] {if updated_thumbnail {- model.set_thumbnail(0, thumbnail.image_snapshot());+ // arrived long ago: its fade-in is over, so the cached and the fresh+ // draw show it the same way+ let arrival = Instant::now().checked_sub(Duration::from_secs(60)).unwrap();+ model.set_thumbnail(0, thumbnail.image_snapshot(), arrival);}assert!(draw(&mut layout, &state, &model, &scroll, 2., true)@@ -1072,6 +1225,7 @@ mod tests {"aspect={aspect}, updated_thumbnail={updated_thumbnail}");}+ // The panel slides while the views change: a moved canvas gets a fresh cachescroll.audio = 0;model.thumbnails[0] = None;}