Add Store support and unsigned app releases

This commit is contained in:
Tamas Csikel
2026-10-25 14:11:49 +01:00
parent 1694cc4858
commit bcc7bc64c0
38 changed files with 12394 additions and 5 deletions

103
sf-ui/src/dev.rs Normal file
View File

@@ -0,0 +1,103 @@
//! Dev helper, built into every [`crate::Glass`] window: scripted key presses
//! and a PNG snapshot of the window, so a UI can be checked (by you, a CI job
//! or an AI) without anyone at the screen.
//!
//! - `SF_UI_SIZE=1920x1080`: physical window size.
//! - `SF_UI_KEYS="down down right enter wait esc"`: keys sent one by one
//! (left, right, up, down, enter, esc, back = esc, backspace, space;
//! a single character types it, `wait` = pause,
//! `hold` = enter held 0.8 s), starting after 1.5 s, every 0.6 s.
//! - `SF_UI_SNAPSHOT=out.png`: saves the frame and quits, 1.5 s after the
//! last key (or after `SF_UI_SNAPSHOT_MS` milliseconds).
use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Duration;
use slint::ComponentHandle;
use slint::platform::{Key, WindowEvent};
const FIRST_KEY_MS: u64 = 1500;
const KEY_STEP_MS: u64 = 600;
/// A snapshot waiting to be taken (shared with the rendering notifier).
#[derive(Default)]
pub(crate) struct Snapshot {
pub(crate) path: RefCell<Option<PathBuf>>,
pub(crate) due: Cell<bool>,
}
pub(crate) fn setup<C: ComponentHandle + 'static>(ui: &C) -> Rc<Snapshot> {
let snap = Rc::new(Snapshot::default());
if let Some((w, h)) = std::env::var("SF_UI_SIZE").ok().and_then(|s| {
let (w, h) = s.split_once('x')?;
Some((w.trim().parse().ok()?, h.trim().parse().ok()?))
}) {
ui.window().set_size(slint::PhysicalSize::new(w, h));
}
let keys: Vec<String> =
std::env::var("SF_UI_KEYS").map(|s| s.split_whitespace().map(str::to_string).collect()).unwrap_or_default();
let mut at = FIRST_KEY_MS;
for k in &keys {
let hold = k == "hold";
let text: Option<slint::SharedString> = match k.to_lowercase().as_str() {
"hold" | "enter" => Some(Key::Return.into()),
"left" => Some(Key::LeftArrow.into()),
"right" => Some(Key::RightArrow.into()),
"up" => Some(Key::UpArrow.into()),
"down" => Some(Key::DownArrow.into()),
"esc" | "back" => Some(Key::Escape.into()),
"backspace" => Some(Key::Backspace.into()),
"space" => Some(" ".into()),
"wait" => None,
_ if k.chars().count() == 1 => Some(k.as_str().into()),
_ => None,
};
let start = at;
at += if hold { 2 * KEY_STEP_MS } else { KEY_STEP_MS };
let Some(text) = text else { continue };
let weak = ui.as_weak();
let t = text.clone();
slint::Timer::single_shot(Duration::from_millis(start), move || {
if let Some(ui) = weak.upgrade() {
ui.window().dispatch_event(WindowEvent::KeyPressed { text: t.clone() });
if !hold {
ui.window().dispatch_event(WindowEvent::KeyReleased { text: t });
}
}
});
if hold {
let weak = ui.as_weak();
slint::Timer::single_shot(Duration::from_millis(start + 800), move || {
if let Some(ui) = weak.upgrade() {
ui.window().dispatch_event(WindowEvent::KeyReleased { text });
}
});
}
}
if let Some(path) = std::env::var_os("SF_UI_SNAPSHOT").map(PathBuf::from) {
let ms = std::env::var("SF_UI_SNAPSHOT_MS").ok().and_then(|s| s.parse().ok()).unwrap_or(at + 1500);
*snap.path.borrow_mut() = Some(path);
let s = snap.clone();
slint::Timer::single_shot(Duration::from_millis(ms), move || s.due.set(true));
}
snap
}
/// Writes top-down RGBA8 pixels as a PNG.
pub(crate) fn save_png(path: &std::path::Path, w: u32, h: u32, rgba: &[u8]) -> anyhow::Result<()> {
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
let mut enc = png::Encoder::new(file, w, h);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
// The window has no meaningful alpha: make every pixel opaque.
let mut data = rgba.to_vec();
for px in data.chunks_exact_mut(4) {
px[3] = 255;
}
enc.write_header()?.write_image_data(&data)?;
Ok(())
}

386
sf-ui/src/glass.rs Normal file
View File

@@ -0,0 +1,386 @@
//! The Liquid Glass layer for a Slint window: install it once, then tell it
//! each frame which panels to draw (usually the `[GlassRect]` arrays your
//! .slint file exports), and set the backdrop (palette, picture, video).
//!
//! ```ignore
//! sf_ui::init()?; // before creating the window
//! let ui = App::new()?;
//! ui.sf_ui_setup(); // from sf_ui::glue!(App)
//! let glass = sf_ui::Glass::install(&ui, |ui, panels| {
//! panels.extend(ui.get_glass().iter());
//! })?;
//! glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
//! ui.run()?;
//! ```
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Instant;
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use crate::render::{Frame, GlassRenderer, ImageDraw, ImageId, Nv12Frame, Panel, Quality, VideoDraw};
use crate::Palette;
/// Time constant of palette and brightness changes (seconds).
const EASE: f32 = 0.35;
/// Crossfade time of pictures and video (seconds).
const FADE: f32 = 0.45;
/// A picture for the backdrop (artwork behind a details page, a hero...).
/// Glass panels refract and frost it like the gradient.
#[derive(Clone)]
pub struct Backdrop {
pixels: SharedPixelBuffer<Rgba8Pixel>,
dim: f32,
fade_left: f32,
fade_bottom: f32,
align: [f32; 2],
sharp: bool,
}
impl Backdrop {
/// Defaults: slightly dimmed, darker towards the left and bottom (room
/// for titles), sharp, cropped around the centre.
pub fn new(pixels: SharedPixelBuffer<Rgba8Pixel>) -> Backdrop {
Backdrop { pixels, dim: 0.12, fade_left: 0.75, fade_bottom: 0.6, align: [0.5, 0.35], sharp: true }
}
/// Darkens the whole picture: 0 = as is, 1 = black.
pub fn dim(mut self, v: f32) -> Self {
self.dim = v.clamp(0.0, 1.0);
self
}
/// Darkening towards the left edge, 0..1.
pub fn fade_left(mut self, v: f32) -> Self {
self.fade_left = v.clamp(0.0, 1.0);
self
}
/// Darkening towards the bottom edge, 0..1.
pub fn fade_bottom(mut self, v: f32) -> Self {
self.fade_bottom = v.clamp(0.0, 1.0);
self
}
/// Which part stays visible when cropped (0..1 per axis, 0.5 = centre).
pub fn align(mut self, x: f32, y: f32) -> Self {
self.align = [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)];
self
}
/// Soft: only the blurred low-resolution copy shows (a frosted wallpaper).
pub fn soft(mut self) -> Self {
self.sharp = false;
self
}
}
/// Where video frames come from (see `sf_ui::video::Player`, or your own
/// decoder). Called once per rendered frame on the UI thread.
pub trait VideoSource {
/// The newest frame since the last call, if any.
fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>>;
}
/// Collects the glass panels of one frame, in logical pixels (the units of
/// your .slint file). Draw order is push order: later panels lie on top.
pub struct Panels {
scale: f32,
out: Vec<Panel>,
}
impl Panels {
/// One panel (logical px).
pub fn push(&mut self, panel: impl Into<Panel>) {
let p = panel.into();
if p.alpha > 0.002 && p.w > 0.0 && p.h > 0.0 {
self.out.push(p.scaled(self.scale));
}
}
/// Many panels, e.g. `panels.extend(ui.get_glass().iter())`.
pub fn extend<T: Into<Panel>>(&mut self, panels: impl IntoIterator<Item = T>) {
for p in panels {
self.push(p);
}
}
}
struct Slot {
backdrop: Backdrop,
id: Option<ImageId>,
alpha: f32,
target: f32,
}
struct State {
palette: [f32; 9],
palette_target: [f32; 9],
brightness: f32,
brightness_target: f32,
images: Vec<Slot>,
free: Vec<ImageId>,
video: Option<Rc<dyn VideoSource>>,
video_alpha: f32,
video_on: bool,
clear_video: bool,
light: f32,
zoom: f32,
last: f32,
quality: Quality,
}
/// Handle to an installed glass layer (cheap to clone).
#[derive(Clone)]
pub struct Glass {
state: Rc<RefCell<State>>,
}
impl Glass {
/// Draws the glass layer under `ui`'s window. `panels` runs before every
/// frame and adds that frame's panels. The backdrop animates, so frames
/// keep coming (vsync-limited).
///
/// Call [`crate::init`] before creating the window: the layer needs the
/// OpenGL (FemtoVG) renderer.
pub fn install<C: ComponentHandle + 'static>(
ui: &C,
mut panels: impl FnMut(&C, &mut Panels) + 'static,
) -> anyhow::Result<Glass> {
let neutral = Palette::NEUTRAL.to_floats();
let state = Rc::new(RefCell::new(State {
palette: neutral,
palette_target: neutral,
brightness: 1.0,
brightness_target: 1.0,
images: Vec::new(),
free: Vec::new(),
video: None,
video_alpha: 0.0,
video_on: false,
clear_video: false,
light: 0.0,
zoom: 1.0,
last: 0.0,
quality: Quality::Full,
}));
let glass = Glass { state: state.clone() };
let snapshot = crate::dev::setup(ui);
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
let start = Instant::now();
let weak = ui.as_weak();
ui.window()
.set_rendering_notifier(move |rs, api| match rs {
slint::RenderingState::RenderingSetup => {
let slint::GraphicsAPI::NativeOpenGL { get_proc_address } = api else {
log::error!("sf-ui: the glass layer needs OpenGL (call sf_ui::init() first)");
return;
};
let gl = unsafe { glow::Context::from_loader_function_cstr(|s| get_proc_address(s)) };
match unsafe { GlassRenderer::new(gl) } {
Ok(r) => *renderer.borrow_mut() = Some(r),
Err(e) => log::error!("sf-ui: glass layer disabled: {e:#}"),
}
}
slint::RenderingState::BeforeRendering => {
let mut guard = renderer.borrow_mut();
let (Some(ui), Some(r)) = (weak.upgrade(), guard.as_mut()) else { return };
let time = start.elapsed().as_secs_f32();
let size = ui.window().size();
let scale = ui.window().scale_factor();
let mut list = Panels { scale, out: Vec::new() };
panels(&ui, &mut list);
let mut st = state.borrow_mut();
let dt = (time - st.last).clamp(0.0, 0.25);
st.last = time;
st.step(dt);
// SAFETY: the rendering notifier runs with the GL context current.
unsafe { st.sync_images(r) };
if std::mem::take(&mut st.clear_video) {
r.clear_video();
}
let draws: Vec<ImageDraw> = st
.images
.iter()
.filter_map(|s| {
Some(ImageDraw {
image: s.id?,
alpha: s.alpha,
dim: s.backdrop.dim,
fade_left: s.backdrop.fade_left,
fade_bottom: s.backdrop.fade_bottom,
align: s.backdrop.align,
sharp: s.backdrop.sharp,
})
})
.collect();
let video = st.video.clone();
let frame_box = video.as_ref().and_then(|v| v.take_frame());
let angle = -2.25 + 0.10 * (time * 0.35).sin() + st.light;
let frame = Frame {
width: size.width,
height: size.height,
scale,
time,
palette: st.palette,
brightness: st.brightness,
light: [angle.cos(), angle.sin()],
zoom: st.zoom,
images: &draws,
video: (st.video_alpha > 0.002 || frame_box.is_some())
.then(|| VideoDraw { frame: frame_box.as_deref(), alpha: st.video_alpha }),
rects: list.out,
quality: st.quality,
};
drop(st);
// SAFETY: as above.
unsafe { r.render(&frame) };
}
slint::RenderingState::AfterRendering => {
let Some(ui) = weak.upgrade() else { return };
if snapshot.due.get() {
if let (Some(path), Some(r)) = (snapshot.path.borrow_mut().take(), renderer.borrow().as_ref()) {
let size = ui.window().size();
// SAFETY: after Slint rendered, context current.
let px = unsafe { r.read_pixels(size.width, size.height) };
match crate::dev::save_png(&path, size.width, size.height, &px) {
Ok(()) => log::info!("sf-ui: snapshot {}", path.display()),
Err(e) => log::error!("sf-ui: snapshot {}: {e:#}", path.display()),
}
let _ = slint::quit_event_loop();
}
}
ui.window().request_redraw();
}
slint::RenderingState::RenderingTeardown => {
if let Some(mut r) = renderer.borrow_mut().take() {
unsafe { r.destroy() };
}
// Textures died with the context: upload again if it comes back.
for s in state.borrow_mut().images.iter_mut() {
s.id = None;
}
}
_ => {}
})
.map_err(|e| anyhow::anyhow!("sf-ui: rendering notifier: {e:?}"))?;
Ok(glass)
}
/// The backdrop gradient's colours; eases over from the current ones.
pub fn set_palette(&self, palette: Palette) {
self.state.borrow_mut().palette_target = palette.to_floats();
}
/// Backdrop brightness, 0..1 (1 = full). Lower it to calm the backdrop
/// behind dense content.
pub fn set_brightness(&self, v: f32) {
self.state.borrow_mut().brightness_target = v.clamp(0.0, 1.0);
}
/// A picture over the gradient (crossfades from the previous one), or
/// `None` to fade back to the gradient.
pub fn set_backdrop(&self, backdrop: Option<Backdrop>) {
let mut st = self.state.borrow_mut();
match backdrop {
Some(b) => {
// Already showing this very picture: keep it.
if let Some(last) = st.images.last_mut() {
if last.backdrop.pixels.as_bytes().as_ptr() == b.pixels.as_bytes().as_ptr() {
last.backdrop = b;
last.target = 1.0;
return;
}
}
st.images.push(Slot { backdrop: b, id: None, alpha: 0.0, target: 1.0 });
}
None => {
for s in st.images.iter_mut() {
s.target = 0.0;
}
}
}
}
/// Video as the backdrop (glass refracts the film), or `None` to fade it
/// out. The source is polled once per frame.
pub fn set_video(&self, source: Option<Rc<dyn VideoSource>>) {
let mut st = self.state.borrow_mut();
st.video_on = source.is_some();
if source.is_some() {
st.video = source;
st.clear_video = true;
}
}
/// Turns the key light (radians, small values like ±0.3), e.g. to follow
/// the focus across the screen.
pub fn set_light(&self, offset: f32) {
self.state.borrow_mut().light = offset;
}
/// How much of the glass effect to draw ([`Quality::Light`] or
/// [`Quality::Flat`] on weaker hardware).
pub fn set_quality(&self, q: Quality) {
self.state.borrow_mut().quality = q;
}
/// Zooms the backdrop gradient (1 = none).
pub fn set_zoom(&self, zoom: f32) {
self.state.borrow_mut().zoom = zoom.max(0.1);
}
}
impl State {
fn step(&mut self, dt: f32) {
let k = 1.0 - (-dt / EASE).exp();
for (c, t) in self.palette.iter_mut().zip(self.palette_target) {
*c += (t - *c) * k;
}
self.brightness += (self.brightness_target - self.brightness) * k;
let fade = dt / FADE;
for s in self.images.iter_mut() {
s.alpha = if s.target > s.alpha { (s.alpha + fade).min(s.target) } else { (s.alpha - fade).max(s.target) };
}
// A picture fully covered by a newer, opaque one is no longer needed;
// faded-out ones neither.
let covered = self.images.iter().rposition(|s| s.alpha >= 0.999).unwrap_or(0);
let mut i = 0;
self.images.retain(|s| {
let keep = i >= covered && !(s.target == 0.0 && s.alpha <= 0.0);
i += 1;
if !keep {
if let Some(id) = s.id {
self.free.push(id);
}
}
keep
});
let target = if self.video_on { 1.0 } else { 0.0 };
self.video_alpha = if target > self.video_alpha {
(self.video_alpha + dt / 0.3).min(1.0)
} else {
(self.video_alpha - dt / 0.3).max(0.0)
};
if !self.video_on && self.video_alpha <= 0.0 {
self.video = None;
}
}
unsafe fn sync_images(&mut self, r: &mut GlassRenderer) {
for id in self.free.drain(..) {
unsafe { r.free_image(id) };
}
for s in self.images.iter_mut().filter(|s| s.id.is_none()) {
let px = &s.backdrop.pixels;
match unsafe { r.upload_image(px.width(), px.height(), px.as_bytes()) } {
Ok(id) => s.id = Some(id),
Err(e) => {
log::warn!("sf-ui: backdrop picture: {e:#}");
s.target = 0.0;
s.alpha = 0.0;
}
}
}
}
}

259
sf-ui/src/images.rs Normal file
View File

@@ -0,0 +1,259 @@
//! Artwork over HTTP(S): downloaded, decoded and scaled on worker threads,
//! kept in a memory cache, handed to you on the UI thread.
//!
//! ```ignore
//! let images = sf_ui::images::Images::new(256 << 20);
//! images.load(&poster_url, (240, 360), move |img| card.set_image(img));
//! ```
//!
//! Sizes are the size you show the picture at, in *physical* pixels (design
//! px × the window's scale): the picture is scaled down to cover that box
//! (never up), so a 4K TV gets sharper artwork and a 1080p one uses less memory.
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::io::Read;
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use slint::{Rgba8Pixel, SharedPixelBuffer};
/// Bigger downloads are refused.
const MAX_DOWNLOAD: u64 = 24 << 20;
const WORKERS: usize = 4;
type Pixels = SharedPixelBuffer<Rgba8Pixel>;
type Key = (String, u32, u32);
type Waiter = Box<dyn FnOnce(&Pixels)>;
struct Job {
owner: u64,
key: Key,
}
struct Inner {
id: u64,
budget: usize,
used: RefCell<usize>,
cache: RefCell<HashMap<Key, Pixels>>,
order: RefCell<VecDeque<Key>>,
waiting: RefCell<HashMap<Key, Vec<Waiter>>>,
jobs: Mutex<Option<mpsc::Sender<()>>>,
queue: Arc<Mutex<VecDeque<Job>>>,
}
thread_local! {
static OWNERS: RefCell<HashMap<u64, Weak<Inner>>> = RefCell::new(HashMap::new());
}
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
/// The image loader and cache (cheap to clone; use it on the UI thread).
#[derive(Clone)]
pub struct Images {
inner: Rc<Inner>,
}
impl Images {
/// `budget`: bytes of decoded pixels to keep (e.g. `256 << 20`).
pub fn new(budget: usize) -> Images {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let queue: Arc<Mutex<VecDeque<Job>>> = Arc::default();
let (tx, rx) = mpsc::channel::<()>();
let rx = Arc::new(Mutex::new(rx));
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(30)))
.user_agent("SmartFox sf-ui")
.build()
.into();
for _ in 0..WORKERS {
let rx = rx.clone();
let queue = queue.clone();
let agent = agent.clone();
std::thread::spawn(move || {
// Wake-ups come over the channel; the newest request is served first
// (what the user looks at now), from the shared queue.
while rx.lock().unwrap().recv().is_ok() {
let Some(job) = queue.lock().unwrap().pop_back() else { continue };
let result = fetch(&agent, &job.key.0, job.key.1, job.key.2);
if let Err(e) = &result {
log::debug!("image {}: {e:#}", job.key.0);
}
let (owner, key) = (job.owner, job.key);
let _ = slint::invoke_from_event_loop(move || deliver(owner, key, result.ok()));
}
});
}
let inner = Rc::new(Inner {
id,
budget,
used: RefCell::new(0),
cache: RefCell::default(),
order: RefCell::default(),
waiting: RefCell::default(),
jobs: Mutex::new(Some(tx)),
queue,
});
OWNERS.with(|o| o.borrow_mut().insert(id, Rc::downgrade(&inner)));
Images { inner }
}
/// Loads `url` scaled to cover `size` (physical px) and calls `done` with
/// it on the UI thread: at once if cached, later otherwise. On failure
/// `done` is not called.
pub fn load(&self, url: &str, size: (u32, u32), done: impl FnOnce(slint::Image) + 'static) {
self.load_pixels(url, size, move |px| done(slint::Image::from_rgba8(px.clone())));
}
/// Like [`Images::load`], but hands over the pixels (for
/// [`crate::Backdrop`] or your own processing).
pub fn load_pixels(&self, url: &str, size: (u32, u32), done: impl FnOnce(&Pixels) + 'static) {
if url.is_empty() {
return;
}
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
if let Some(px) = self.inner.cache.borrow().get(&key).cloned() {
self.touch(&key);
done(&px);
return;
}
let mut waiting = self.inner.waiting.borrow_mut();
if let Some(list) = waiting.get_mut(&key) {
list.push(Box::new(done));
return;
}
waiting.insert(key.clone(), vec![Box::new(done)]);
drop(waiting);
self.inner.queue.lock().unwrap().push_back(Job { owner: self.inner.id, key });
if let Some(tx) = self.inner.jobs.lock().unwrap().as_ref() {
let _ = tx.send(());
}
}
/// The cached picture, if it is already loaded.
pub fn cached(&self, url: &str, size: (u32, u32)) -> Option<slint::Image> {
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
self.inner.cache.borrow().get(&key).map(|px| slint::Image::from_rgba8(px.clone()))
}
/// Drops requests that have not started yet (e.g. after leaving a screen).
pub fn cancel_pending(&self) {
let mut q = self.inner.queue.lock().unwrap();
let mut waiting = self.inner.waiting.borrow_mut();
for job in q.drain(..) {
waiting.remove(&job.key);
}
}
fn touch(&self, key: &Key) {
let mut order = self.inner.order.borrow_mut();
if let Some(i) = order.iter().position(|k| k == key) {
let k = order.remove(i).unwrap();
order.push_back(k);
}
}
}
impl Inner {
fn insert(&self, key: Key, px: Pixels) {
let bytes = px.as_bytes().len();
let mut cache = self.cache.borrow_mut();
let mut order = self.order.borrow_mut();
let mut used = self.used.borrow_mut();
while *used + bytes > self.budget {
let Some(old) = order.pop_front() else { break };
if let Some(p) = cache.remove(&old) {
*used -= p.as_bytes().len();
}
}
*used += bytes;
order.push_back(key.clone());
cache.insert(key, px);
}
}
impl Drop for Inner {
fn drop(&mut self) {
// Ends the worker threads.
self.jobs.lock().unwrap().take();
let id = self.id;
let _ = OWNERS.try_with(|o| o.borrow_mut().remove(&id));
}
}
fn deliver(owner: u64, key: Key, px: Option<Pixels>) {
let Some(inner) = OWNERS.with(|o| o.borrow().get(&owner).and_then(Weak::upgrade)) else { return };
let waiters = inner.waiting.borrow_mut().remove(&key).unwrap_or_default();
let Some(px) = px else { return };
inner.insert(key, px.clone());
for w in waiters {
w(&px);
}
}
fn fetch(agent: &ureq::Agent, url: &str, w: u32, h: u32) -> anyhow::Result<Pixels> {
let mut resp = agent.get(url).call()?;
let mut bytes = Vec::new();
resp.body_mut().as_reader().take(MAX_DOWNLOAD + 1).read_to_end(&mut bytes)?;
anyhow::ensure!((bytes.len() as u64) <= MAX_DOWNLOAD, "larger than {MAX_DOWNLOAD} bytes");
decode(&bytes, w, h)
}
/// Decodes and scales down to cover `w` x `h` (never up).
pub fn decode(bytes: &[u8], w: u32, h: u32) -> anyhow::Result<Pixels> {
let img = image::load_from_memory(bytes)?;
let (iw, ih) = (img.width().max(1), img.height().max(1));
let k = (w as f32 / iw as f32).max(h as f32 / ih as f32);
let img = if k < 0.98 {
let (nw, nh) = (((iw as f32 * k).round() as u32).max(1), ((ih as f32 * k).round() as u32).max(1));
img.resize_exact(nw, nh, image::imageops::FilterType::Triangle)
} else {
img
};
let rgba = img.into_rgba8();
Ok(SharedPixelBuffer::clone_from_slice(rgba.as_raw(), rgba.width(), rgba.height()))
}
/// The average colour of a picture (for a matching [`crate::Palette`]),
/// leaning towards its saturated parts.
pub fn average_color(px: &Pixels) -> slint::Color {
let (mut r, mut g, mut b, mut n) = (0f64, 0f64, 0f64, 0f64);
let bytes = px.as_bytes();
for p in bytes.chunks_exact(4).step_by(7) {
let (pr, pg, pb) = (p[0] as f64, p[1] as f64, p[2] as f64);
let max = pr.max(pg).max(pb);
let min = pr.min(pg).min(pb);
let wgt = 0.15 + (max - min) / 255.0 + max / 510.0;
r += pr * wgt;
g += pg * wgt;
b += pb * wgt;
n += wgt;
}
if n == 0.0 {
return slint::Color::from_rgb_u8(0x2a, 0x31, 0x40);
}
slint::Color::from_rgb_u8((r / n) as u8, (g / n) as u8, (b / n) as u8)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scales_to_cover() {
let mut png = Vec::new();
let img = image::RgbaImage::from_pixel(400, 600, image::Rgba([200, 40, 30, 255]));
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let px = decode(&png, 100, 100).unwrap();
assert_eq!((px.width(), px.height()), (100, 150));
let px = decode(&png, 1000, 1000).unwrap();
assert_eq!((px.width(), px.height()), (400, 600));
let c = average_color(&px);
assert!(c.red() > 150 && c.green() < 80);
}
}

191
sf-ui/src/lib.rs Normal file
View File

@@ -0,0 +1,191 @@
//! sf-ui: the SmartFox TV UI kit for Slint apps.
//!
//! - **Liquid Glass** ([`Glass`]): the refracting, frosted glass of the
//! SmartFox launcher, drawn by an OpenGL layer under your Slint UI, over an
//! animated palette backdrop, a picture or a playing video.
//! - **Slint components** (`@sf-ui/sf-ui.slint`): design tokens (`Tv`), text
//! styles, glass panes, buttons, chips, a progress bar, an on-screen
//! keyboard, icons and the Onest font.
//! - **Images** ([`images::Images`], feature `images`): artwork over HTTP,
//! decoded and scaled off the UI thread, cached.
//! - **Video** (`video::Player`, feature `video`, Linux): GStreamer playback
//! with hardware decoding, its frames shown as the glass backdrop.
//!
//! Guide: `docs/sf-ui.md` in the SmartFox repository.
pub mod render;
mod dev;
mod glass;
#[cfg(feature = "images")]
pub mod images;
pub mod text;
#[cfg(feature = "video")]
pub mod video;
pub use glass::{Backdrop, Glass, Panels, VideoSource};
pub use render::{Matrix, Nv12Frame, Panel, Quality};
/// Selects Slint's OpenGL renderer (FemtoVG), which the glass layer draws
/// with. Call it first in `main`, before creating any window.
pub fn init() -> anyhow::Result<()> {
slint::BackendSelector::new()
.renderer_name("femtovg".into())
.select()
.map_err(|e| anyhow::anyhow!("selecting the femtovg (OpenGL) renderer: {e}"))
}
/// The backdrop gradient's three colours: highlight, mid, deep. Use the
/// `palette` of your app.toml, or one per screen / per focused item.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Palette {
pub highlight: slint::Color,
pub mid: slint::Color,
pub deep: slint::Color,
}
impl Palette {
/// The neutral system palette (no app colour).
pub const NEUTRAL: Palette = Palette {
highlight: slint::Color::from_rgb_u8(0x9a, 0xa4, 0xb5),
mid: slint::Color::from_rgb_u8(0x2a, 0x31, 0x40),
deep: slint::Color::from_rgb_u8(0x06, 0x07, 0x0a),
};
pub fn new(highlight: slint::Color, mid: slint::Color, deep: slint::Color) -> Palette {
Palette { highlight, mid, deep }
}
/// From three "#rrggbb" strings (as in app.toml); bad ones fall back to
/// the neutral palette's colour.
pub fn from_hex(hex: [&str; 3]) -> Palette {
let n = Palette::NEUTRAL;
Palette {
highlight: parse_hex(hex[0]).unwrap_or(n.highlight),
mid: parse_hex(hex[1]).unwrap_or(n.mid),
deep: parse_hex(hex[2]).unwrap_or(n.deep),
}
}
/// A palette from one colour, e.g. the average colour of a poster:
/// a lighter highlight, the colour itself, a near-black deep tone.
pub fn from_color(c: slint::Color) -> Palette {
let [r, g, b] = rgb(c);
let mix = |k: f32, t: f32| -> slint::Color {
let f = |v: f32| ((v * k + t * (1.0 - k)).clamp(0.0, 1.0) * 255.0) as u8;
slint::Color::from_rgb_u8(f(r), f(g), f(b))
};
Palette { highlight: mix(0.7, 1.0), mid: mix(0.55, 0.0), deep: mix(0.08, 0.0) }
}
/// rgb 0..1 for the renderer.
pub fn to_floats(self) -> [f32; 9] {
let mut out = [0.0; 9];
for (i, c) in [self.highlight, self.mid, self.deep].into_iter().enumerate() {
out[i * 3..i * 3 + 3].copy_from_slice(&rgb(c));
}
out
}
}
/// "#rrggbb" or "rrggbb".
pub fn parse_hex(hex: &str) -> Option<slint::Color> {
let h = hex.trim().trim_start_matches('#');
let v = u32::from_str_radix(h.get(..6)?, 16).ok()?;
Some(slint::Color::from_rgb_u8((v >> 16) as u8, (v >> 8) as u8, v as u8))
}
fn rgb(c: slint::Color) -> [f32; 3] {
[c.red() as f32 / 255.0, c.green() as f32 / 255.0, c.blue() as f32 / 255.0]
}
impl Panel {
/// From the fields of a Slint `GlassRect` (used by [`glue!`]).
#[allow(clippy::too_many_arguments)]
pub fn from_slint(
x: f32,
y: f32,
w: f32,
h: f32,
r: f32,
focus: f32,
alpha: f32,
blur: f32,
glow: slint::Color,
tint: slint::Color,
group: i32,
) -> Panel {
let [tr, tg, tb] = rgb(tint);
Panel {
x,
y,
w,
h,
radius: r,
focus,
alpha,
blur,
glow: rgb(glow),
group: group as f32,
tint: [tr, tg, tb, tint.alpha() as f32 / 255.0],
}
}
}
/// Connects the types Slint generated in *your* crate to sf-ui. Put it once
/// next to `slint::include_modules!()`, with your root component's name:
///
/// ```ignore
/// slint::include_modules!();
/// sf_ui::glue!(App);
/// ```
///
/// It makes `GlassRect` convertible to [`Panel`] (so `panels.extend(...)`
/// takes your `[GlassRect]` arrays) and adds `App::sf_ui_setup()`, which
/// wires the Slint helper callbacks (`SfText`). Your main .slint file must
/// export the helpers: `export { Tv, SfText } from "@sf-ui/sf-ui.slint";`.
#[macro_export]
macro_rules! glue {
($app:ident) => {
impl ::core::convert::From<GlassRect> for $crate::Panel {
fn from(g: GlassRect) -> Self {
$crate::Panel::from_slint(g.x, g.y, g.w, g.h, g.r, g.focus, g.alpha, g.blur, g.glow.color(), g.tint.color(), g.group)
}
}
impl $app {
/// Wires the sf-ui Slint helpers (text editing for the keyboard).
/// Call it once after creating the window.
#[allow(dead_code)]
pub fn sf_ui_setup(&self) {
use ::slint::ComponentHandle as _;
let t = self.global::<SfText>();
t.on_drop_last(|s| $crate::text::drop_last(&s).into());
t.on_dots(|n| $crate::text::dots(n.max(0) as usize).into());
t.on_truncate(|s, n| $crate::text::truncate(&s, n.max(0) as usize).into());
t.on_typable(|s| $crate::text::typable(&s).into());
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_colours() {
assert_eq!(parse_hex("#ff7a35"), Some(slint::Color::from_rgb_u8(0xff, 0x7a, 0x35)));
assert_eq!(parse_hex("121317"), Some(slint::Color::from_rgb_u8(0x12, 0x13, 0x17)));
assert_eq!(parse_hex("#12"), None);
let p = Palette::from_hex(["#ffffff", "nope", "#000000"]);
assert_eq!(p.mid, Palette::NEUTRAL.mid);
assert_eq!(p.to_floats()[0], 1.0);
}
#[test]
fn panel_scaling() {
let p = Panel { x: 10.0, y: 20.0, w: 30.0, h: 40.0, radius: 5.0, alpha: 1.0, ..Panel::default() }.scaled(2.0);
assert_eq!((p.x, p.y, p.w, p.h, p.radius), (20.0, 40.0, 60.0, 80.0, 10.0));
}
}

167
sf-ui/src/render/mod.rs Normal file
View File

@@ -0,0 +1,167 @@
//! The low-level Liquid Glass renderer: an OpenGL pass drawn *under* the
//! Slint UI. Most apps use [`crate::Glass`] instead, which drives this from a
//! Slint rendering notifier; use this module directly only if you need your
//! own notifier (the launcher does, for its dev snapshots).
//!
//! Per frame: the backdrop (animated gradient, optional pictures, optional
//! video) goes into a small mipmapped texture and onto the window; then every
//! glass panel is drawn as its own quad, refracting and frosting that texture.
mod renderer;
mod shaders;
pub use renderer::GlassRenderer;
/// Panels drawn per frame at most (each one is its own small draw call).
pub const MAX_RECTS: usize = 48;
/// Members of one merged (liquid) group at most.
pub const MAX_GROUP: usize = 4;
/// One glass panel. In [`Frame`] it is in physical pixels (top-left origin);
/// [`crate::Panels`] takes it in logical pixels and scales it.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Panel {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub radius: f32,
/// 0..1, brightens the rim and adds the accent glow.
pub focus: f32,
pub alpha: f32,
/// Frost: mip level of the backdrop seen through it (higher = blurrier).
/// Negative = nested glass that sits on another pane.
pub blur: f32,
/// Accent light (rgb 0..1) for focus glow and rim.
pub glow: [f32; 3],
/// Consecutive panels with the same group (> 0) melt into one shape.
pub group: f32,
/// rgb + amount (0..1).
pub tint: [f32; 4],
}
impl Panel {
/// The same panel with every length multiplied by `k` (logical → physical).
pub fn scaled(mut self, k: f32) -> Panel {
self.x *= k;
self.y *= k;
self.w *= k;
self.h *= k;
self.radius *= k;
self
}
}
/// A picture uploaded with [`GlassRenderer::upload_image`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ImageId(pub(crate) u32);
/// One picture on the backdrop, drawn over the gradient (and under the glass).
#[derive(Debug, Clone, Copy)]
pub struct ImageDraw {
pub image: ImageId,
/// 0..1, for crossfades.
pub alpha: f32,
/// Darkens the whole picture (0 = as is).
pub dim: f32,
/// Darkens towards the left edge (room for a title), 0..1.
pub fade_left: f32,
/// Darkens towards the bottom edge, 0..1.
pub fade_bottom: f32,
/// Which part stays visible when the picture is cropped to the screen
/// (0..1 per axis, 0.5 = centre).
pub align: [f32; 2],
/// Drawn sharp at full resolution. When false only the soft (blurred,
/// low resolution) copy shows, like a frosted wallpaper.
pub sharp: bool,
}
/// Colour matrix of a video frame.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Matrix {
Bt601,
#[default]
Bt709,
Bt2020,
}
/// One decoded video frame in NV12: a full-size Y plane and a half-size
/// plane of interleaved Cb/Cr bytes.
pub trait Nv12Frame {
fn width(&self) -> u32;
fn height(&self) -> u32;
/// Display aspect ratio (width / height, pixel aspect included).
fn aspect(&self) -> f32 {
self.width() as f32 / self.height().max(1) as f32
}
/// Plane 0 (Y) or 1 (CbCr): bytes and the stride (bytes per row).
fn plane(&self, index: usize) -> (&[u8], usize);
fn matrix(&self) -> Matrix {
Matrix::Bt709
}
fn full_range(&self) -> bool {
false
}
}
/// The video layer of a frame. The renderer keeps the last uploaded frame,
/// so `frame` only needs to be set when a new one arrived.
pub struct VideoDraw<'a> {
pub frame: Option<&'a dyn Nv12Frame>,
/// 0..1, for fading in.
pub alpha: f32,
}
/// How much of the glass effect to draw (weaker TVs: lighter modes).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Quality {
/// Refraction, dispersion, Fresnel: the full Liquid Glass.
#[default]
Full,
/// Frosted glass with the lit rim, no lensing.
Light,
/// No frost: tinted panes with the rim only.
Flat,
}
/// Everything the renderer needs for one frame.
pub struct Frame<'a> {
pub width: u32,
pub height: u32,
/// Physical pixels per logical pixel (glass sizes depend on it).
pub scale: f32,
/// Seconds since start (animation clock).
pub time: f32,
/// Backdrop palette (highlight, mid, deep), rgb 0..1 each.
pub palette: [f32; 9],
/// Backdrop brightness, 0..1 (1 = full).
pub brightness: f32,
/// Direction towards the key light (screen space, y down).
pub light: [f32; 2],
/// Backdrop zoom (1 = none), e.g. for a launch fly-in.
pub zoom: f32,
/// Pictures over the gradient, in drawing order.
pub images: &'a [ImageDraw],
pub video: Option<VideoDraw<'a>>,
pub rects: Vec<Panel>,
pub quality: Quality,
}
impl Default for Frame<'_> {
fn default() -> Self {
Frame {
width: 0,
height: 0,
scale: 1.0,
time: 0.0,
palette: crate::Palette::NEUTRAL.to_floats(),
brightness: 1.0,
light: [-0.63, -0.78],
zoom: 1.0,
images: &[],
video: None,
rects: Vec::new(),
quality: Quality::Full,
}
}
}

View File

@@ -0,0 +1,735 @@
//! OpenGL underlay drawn before Slint renders its items.
//!
//! Pass 1 renders the backdrop (gradient, then pictures, then video) into a
//! small, mipmapped texture: that is what the glass refracts and frosts.
//! Pass 2 puts the backdrop on the window: the small texture upscaled, then
//! sharp pictures and the video at full resolution. Pass 3 draws every glass
//! panel as its own quad, covering only the panel and its shadow. Uniform
//! locations are looked up once; GL state is handed back to Slint untouched.
use std::collections::HashMap;
use glow::HasContext;
use super::shaders;
use super::{Frame, ImageDraw, ImageId, MAX_GROUP, MAX_RECTS, Matrix, Nv12Frame, Panel};
/// The backdrop is blurry by design, so it never needs more than this width.
const SCENE_MAX_W: i32 = 640;
type Loc = Option<glow::UniformLocation>;
struct SceneLocs {
res: Loc,
time: Loc,
pal: Loc,
zoom: Loc,
bright: Loc,
}
struct BlitLocs {
scene: Loc,
time: Loc,
}
struct ImageLocs {
image: Loc,
img: Loc,
res: Loc,
align: Loc,
dim: Loc,
fade_left: Loc,
fade_bottom: Loc,
alpha: Loc,
}
struct VideoLocs {
y: Loc,
uv: Loc,
res: Loc,
aspect: Loc,
matrix: Loc,
full: Loc,
alpha: Loc,
}
struct GlassLocs {
box_: Loc,
res: Loc,
scene: Loc,
scale: Loc,
time: Loc,
light: Loc,
count: Loc,
rect: Loc,
param: Loc,
glow: Loc,
tint: Loc,
mode: Loc,
}
struct Image {
tex: glow::Texture,
w: i32,
h: i32,
}
/// The last uploaded video frame.
struct Video {
y: glow::Texture,
uv: glow::Texture,
size: (i32, i32),
aspect: f32,
matrix: Matrix,
full: bool,
ready: bool,
}
pub struct GlassRenderer {
gl: glow::Context,
vao: glow::VertexArray,
scene_prog: glow::Program,
blit_prog: glow::Program,
image_prog: glow::Program,
video_prog: glow::Program,
glass_prog: glow::Program,
scene_locs: SceneLocs,
blit_locs: BlitLocs,
image_locs: ImageLocs,
video_locs: VideoLocs,
glass_locs: GlassLocs,
fbo: glow::Framebuffer,
tex: glow::Texture,
tex_size: (i32, i32),
/// RGBA16F if the driver can render to it (no banding in dark gradients).
half_float: bool,
images: HashMap<u32, Image>,
next_image: u32,
video: Option<Video>,
}
/// GL state we touch and must hand back to the Slint renderer untouched.
struct SavedState {
program: i32,
vao: i32,
array_buffer: i32,
framebuffer: i32,
active_texture: i32,
texture0: i32,
texture1: i32,
viewport: [i32; 4],
blend: bool,
blend_func: [i32; 4],
blend_eq: [i32; 2],
scissor: bool,
depth: bool,
stencil: bool,
cull: bool,
unpack_alignment: i32,
unpack_row_length: i32,
}
impl GlassRenderer {
/// # Safety
/// Must be called with the Slint OpenGL context current.
pub unsafe fn new(gl: glow::Context) -> anyhow::Result<Self> {
unsafe {
let version = gl.get_parameter_string(glow::VERSION);
let is_es = version.contains("OpenGL ES");
log::info!("OpenGL: {version} ({})", gl.get_parameter_string(glow::RENDERER));
let header = if is_es {
"#version 300 es\nprecision highp float;\nprecision highp int;\n"
} else {
"#version 330 core\n"
};
let scene_prog = link(&gl, header, shaders::VERTEX, shaders::SCENE)?;
let blit_prog = link(&gl, header, shaders::VERTEX, shaders::BLIT)?;
let image_prog = link(&gl, header, shaders::VERTEX, shaders::IMAGE)?;
let video_prog = link(&gl, header, shaders::VERTEX, shaders::VIDEO)?;
let glass_prog = link(&gl, header, shaders::QUAD_VERTEX, shaders::GLASS)?;
let loc = |p: glow::Program, name: &str| gl.get_uniform_location(p, name);
let scene_locs = SceneLocs {
res: loc(scene_prog, "uRes"),
time: loc(scene_prog, "uTime"),
pal: loc(scene_prog, "uPal"),
zoom: loc(scene_prog, "uZoom"),
bright: loc(scene_prog, "uBright"),
};
let blit_locs = BlitLocs { scene: loc(blit_prog, "uScene"), time: loc(blit_prog, "uTime") };
let image_locs = ImageLocs {
image: loc(image_prog, "uImage"),
img: loc(image_prog, "uImg"),
res: loc(image_prog, "uRes"),
align: loc(image_prog, "uAlign"),
dim: loc(image_prog, "uDim"),
fade_left: loc(image_prog, "uFadeLeft"),
fade_bottom: loc(image_prog, "uFadeBottom"),
alpha: loc(image_prog, "uAlpha"),
};
let video_locs = VideoLocs {
y: loc(video_prog, "uY"),
uv: loc(video_prog, "uUV"),
res: loc(video_prog, "uRes"),
aspect: loc(video_prog, "uAspect"),
matrix: loc(video_prog, "uMatrix"),
full: loc(video_prog, "uFull"),
alpha: loc(video_prog, "uAlpha"),
};
let glass_locs = GlassLocs {
box_: loc(glass_prog, "uBox"),
res: loc(glass_prog, "uRes"),
scene: loc(glass_prog, "uScene"),
scale: loc(glass_prog, "uScale"),
time: loc(glass_prog, "uTime"),
light: loc(glass_prog, "uLight"),
count: loc(glass_prog, "uCount"),
rect: loc(glass_prog, "uRect"),
param: loc(glass_prog, "uParam"),
glow: loc(glass_prog, "uGlow"),
tint: loc(glass_prog, "uTint"),
mode: loc(glass_prog, "uMode"),
};
let vao = gl.create_vertex_array().map_err(anyhow::Error::msg)?;
let fbo = gl.create_framebuffer().map_err(anyhow::Error::msg)?;
let tex = gl.create_texture().map_err(anyhow::Error::msg)?;
Ok(Self {
gl,
vao,
scene_prog,
blit_prog,
image_prog,
video_prog,
glass_prog,
scene_locs,
blit_locs,
image_locs,
video_locs,
glass_locs,
fbo,
tex,
tex_size: (0, 0),
half_float: true,
images: HashMap::new(),
next_image: 1,
video: None,
})
}
}
unsafe fn save(&self) -> SavedState {
let gl = &self.gl;
unsafe {
let mut viewport = [0; 4];
gl.get_parameter_i32_slice(glow::VIEWPORT, &mut viewport);
let active_texture = gl.get_parameter_i32(glow::ACTIVE_TEXTURE);
gl.active_texture(glow::TEXTURE1);
let texture1 = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D);
gl.active_texture(glow::TEXTURE0);
SavedState {
program: gl.get_parameter_i32(glow::CURRENT_PROGRAM),
vao: gl.get_parameter_i32(glow::VERTEX_ARRAY_BINDING),
array_buffer: gl.get_parameter_i32(glow::ARRAY_BUFFER_BINDING),
framebuffer: gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING),
active_texture,
texture0: gl.get_parameter_i32(glow::TEXTURE_BINDING_2D),
texture1,
viewport,
blend: gl.is_enabled(glow::BLEND),
blend_func: [
gl.get_parameter_i32(glow::BLEND_SRC_RGB),
gl.get_parameter_i32(glow::BLEND_DST_RGB),
gl.get_parameter_i32(glow::BLEND_SRC_ALPHA),
gl.get_parameter_i32(glow::BLEND_DST_ALPHA),
],
blend_eq: [
gl.get_parameter_i32(glow::BLEND_EQUATION_RGB),
gl.get_parameter_i32(glow::BLEND_EQUATION_ALPHA),
],
scissor: gl.is_enabled(glow::SCISSOR_TEST),
depth: gl.is_enabled(glow::DEPTH_TEST),
stencil: gl.is_enabled(glow::STENCIL_TEST),
cull: gl.is_enabled(glow::CULL_FACE),
unpack_alignment: gl.get_parameter_i32(glow::UNPACK_ALIGNMENT),
unpack_row_length: gl.get_parameter_i32(glow::UNPACK_ROW_LENGTH),
}
}
}
unsafe fn restore(&self, s: SavedState) {
let gl = &self.gl;
let nz = |v: i32| std::num::NonZeroU32::new(v as u32);
unsafe {
gl.use_program(nz(s.program).map(glow::NativeProgram));
gl.bind_vertex_array(nz(s.vao).map(glow::NativeVertexArray));
gl.bind_buffer(glow::ARRAY_BUFFER, nz(s.array_buffer).map(glow::NativeBuffer));
gl.bind_framebuffer(glow::FRAMEBUFFER, nz(s.framebuffer).map(glow::NativeFramebuffer));
gl.active_texture(glow::TEXTURE1);
gl.bind_texture(glow::TEXTURE_2D, nz(s.texture1).map(glow::NativeTexture));
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, nz(s.texture0).map(glow::NativeTexture));
gl.active_texture(s.active_texture as u32);
gl.viewport(s.viewport[0], s.viewport[1], s.viewport[2], s.viewport[3]);
let [sr, dr, sa, da] = s.blend_func.map(|v| v as u32);
gl.blend_func_separate(sr, dr, sa, da);
gl.blend_equation_separate(s.blend_eq[0] as u32, s.blend_eq[1] as u32);
let set = |cap, on: bool| if on { gl.enable(cap) } else { gl.disable(cap) };
set(glow::BLEND, s.blend);
set(glow::SCISSOR_TEST, s.scissor);
set(glow::DEPTH_TEST, s.depth);
set(glow::STENCIL_TEST, s.stencil);
set(glow::CULL_FACE, s.cull);
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, s.unpack_alignment);
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, s.unpack_row_length);
}
}
unsafe fn alloc_target(&self, w: i32, h: i32, half_float: bool) -> bool {
let gl = &self.gl;
unsafe {
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
let (internal, ty) =
if half_float { (glow::RGBA16F, glow::HALF_FLOAT) } else { (glow::RGBA8, glow::UNSIGNED_BYTE) };
gl.tex_image_2d(
glow::TEXTURE_2D,
0,
internal as i32,
w,
h,
0,
glow::RGBA,
ty,
glow::PixelUnpackData::Slice(None),
);
set_filter(gl, true);
gl.generate_mipmap(glow::TEXTURE_2D);
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo));
gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(self.tex), 0);
gl.check_framebuffer_status(glow::FRAMEBUFFER) == glow::FRAMEBUFFER_COMPLETE
}
}
unsafe fn ensure_target(&mut self, w: i32, h: i32) {
if self.tex_size == (w, h) {
return;
}
unsafe {
if self.half_float && !self.alloc_target(w, h, true) {
log::info!("glass: RGBA16F not renderable, using RGBA8 for the backdrop");
self.half_float = false;
}
if !self.half_float {
self.alloc_target(w, h, false);
}
}
self.tex_size = (w, h);
}
/// Uploads a picture (RGBA8, top row first) for [`ImageDraw`].
///
/// # Safety
/// Must be called with the context current (inside the rendering notifier).
pub unsafe fn upload_image(&mut self, width: u32, height: u32, rgba: &[u8]) -> anyhow::Result<ImageId> {
let (w, h) = (width as i32, height as i32);
anyhow::ensure!(w > 0 && h > 0 && rgba.len() >= (width * height * 4) as usize, "bad image size");
let gl = &self.gl;
unsafe {
let unpack = (gl.get_parameter_i32(glow::UNPACK_ALIGNMENT), gl.get_parameter_i32(glow::UNPACK_ROW_LENGTH));
let bound = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D);
let tex = gl.create_texture().map_err(anyhow::Error::msg)?;
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
gl.tex_image_2d(
glow::TEXTURE_2D,
0,
glow::RGBA8 as i32,
w,
h,
0,
glow::RGBA,
glow::UNSIGNED_BYTE,
glow::PixelUnpackData::Slice(Some(&rgba[..(width * height * 4) as usize])),
);
set_filter(gl, true);
gl.generate_mipmap(glow::TEXTURE_2D);
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, unpack.0);
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, unpack.1);
gl.bind_texture(glow::TEXTURE_2D, std::num::NonZeroU32::new(bound as u32).map(glow::NativeTexture));
let id = self.next_image;
self.next_image += 1;
self.images.insert(id, Image { tex, w, h });
Ok(ImageId(id))
}
}
/// # Safety
/// Must be called with the context current.
pub unsafe fn free_image(&mut self, id: ImageId) {
if let Some(img) = self.images.remove(&id.0) {
unsafe { self.gl.delete_texture(img.tex) };
}
}
/// Forgets the last video frame (the next one starts from black).
pub fn clear_video(&mut self) {
if let Some(v) = &mut self.video {
v.ready = false;
}
}
unsafe fn upload_video(&mut self, frame: &dyn Nv12Frame) -> anyhow::Result<()> {
let (w, h) = (frame.width() as i32, frame.height() as i32);
anyhow::ensure!(w > 1 && h > 1, "empty video frame");
let (cw, ch) = ((w + 1) / 2, (h + 1) / 2);
let (y, y_stride) = frame.plane(0);
let (uv, uv_stride) = frame.plane(1);
anyhow::ensure!(y_stride >= w as usize && y.len() >= y_stride * (h as usize - 1) + w as usize, "short Y plane");
anyhow::ensure!(
uv_stride >= 2 * cw as usize && uv.len() >= uv_stride * (ch as usize - 1) + 2 * cw as usize,
"short CbCr plane"
);
let gl = &self.gl;
unsafe {
if self.video.is_none() {
let y = gl.create_texture().map_err(anyhow::Error::msg)?;
let uv = gl.create_texture().map_err(anyhow::Error::msg)?;
self.video =
Some(Video { y, uv, size: (0, 0), aspect: 1.0, matrix: Matrix::Bt709, full: false, ready: false });
}
let v = self.video.as_mut().unwrap();
let realloc = v.size != (w, h);
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
let planes = [
(v.y, y, y_stride, w, h, glow::R8, glow::RED, 1usize),
(v.uv, uv, uv_stride, cw, ch, glow::RG8, glow::RG, 2usize),
];
for (tex, data, stride, pw, ph, internal, format, bpp) in planes {
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, (stride / bpp) as i32);
let len = stride * (ph as usize - 1) + pw as usize * bpp;
let pixels = glow::PixelUnpackData::Slice(Some(&data[..len]));
if realloc {
gl.tex_image_2d(glow::TEXTURE_2D, 0, internal as i32, pw, ph, 0, format, glow::UNSIGNED_BYTE, pixels);
set_filter(gl, true);
} else {
gl.tex_sub_image_2d(glow::TEXTURE_2D, 0, 0, 0, pw, ph, format, glow::UNSIGNED_BYTE, pixels);
}
// Mipmaps keep the small backdrop copy free of shimmer.
gl.generate_mipmap(glow::TEXTURE_2D);
}
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
v.size = (w, h);
v.aspect = frame.aspect();
v.matrix = frame.matrix();
v.full = frame.full_range();
v.ready = true;
}
Ok(())
}
/// Pictures and video into the current framebuffer (viewport `w` x `h`).
/// `all`: also the soft-only pictures (the small backdrop copy).
unsafe fn draw_layers(&self, f: &Frame, w: i32, h: i32, all: bool, video_alpha: f32) {
let gl = &self.gl;
unsafe {
gl.enable(glow::BLEND);
gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD);
gl.blend_func_separate(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA, glow::ZERO, glow::ONE);
for d in f.images.iter().filter(|d| d.alpha > 0.002 && (all || d.sharp)) {
let Some(img) = self.images.get(&d.image.0) else { continue };
self.draw_image(img, d, w, h);
}
if let Some(v) = self.video.as_ref().filter(|v| v.ready && video_alpha > 0.002) {
let l = &self.video_locs;
gl.use_program(Some(self.video_prog));
gl.active_texture(glow::TEXTURE1);
gl.bind_texture(glow::TEXTURE_2D, Some(v.uv));
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(v.y));
gl.uniform_1_i32(l.y.as_ref(), 0);
gl.uniform_1_i32(l.uv.as_ref(), 1);
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
gl.uniform_1_f32(l.aspect.as_ref(), v.aspect);
let m = match v.matrix {
Matrix::Bt601 => 0,
Matrix::Bt709 => 1,
Matrix::Bt2020 => 2,
};
gl.uniform_1_i32(l.matrix.as_ref(), m);
gl.uniform_1_i32(l.full.as_ref(), v.full as i32);
gl.uniform_1_f32(l.alpha.as_ref(), video_alpha.clamp(0.0, 1.0));
gl.draw_arrays(glow::TRIANGLES, 0, 3);
}
gl.disable(glow::BLEND);
}
}
unsafe fn draw_image(&self, img: &Image, d: &ImageDraw, w: i32, h: i32) {
let gl = &self.gl;
let l = &self.image_locs;
unsafe {
gl.use_program(Some(self.image_prog));
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(img.tex));
gl.uniform_1_i32(l.image.as_ref(), 0);
gl.uniform_2_f32(l.img.as_ref(), img.w as f32, img.h as f32);
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
gl.uniform_2_f32(l.align.as_ref(), d.align[0], d.align[1]);
gl.uniform_1_f32(l.dim.as_ref(), d.dim);
gl.uniform_1_f32(l.fade_left.as_ref(), d.fade_left);
gl.uniform_1_f32(l.fade_bottom.as_ref(), d.fade_bottom);
gl.uniform_1_f32(l.alpha.as_ref(), d.alpha.clamp(0.0, 1.0));
gl.draw_arrays(glow::TRIANGLES, 0, 3);
}
}
/// # Safety
/// Must be called from the Slint rendering notifier with the context current.
pub unsafe fn render(&mut self, f: &Frame) {
let (w, h) = (f.width as i32, f.height as i32);
if w <= 0 || h <= 0 {
return;
}
unsafe {
let saved = self.save();
let gl = &self.gl;
gl.disable(glow::BLEND);
gl.disable(glow::SCISSOR_TEST);
gl.disable(glow::DEPTH_TEST);
gl.disable(glow::STENCIL_TEST);
gl.disable(glow::CULL_FACE);
let mut video_alpha = 0.0;
if let Some(v) = &f.video {
video_alpha = v.alpha;
if let Some(frame) = v.frame {
if let Err(e) = self.upload_video(frame) {
log::warn!("glass: video frame: {e:#}");
}
}
}
let gl = &self.gl;
gl.bind_vertex_array(Some(self.vao));
// Pass 1: backdrop at low resolution (blurred by the glass anyway).
let sw = (w / 4).clamp(1, SCENE_MAX_W);
let sh = ((sw as i64 * h as i64 / w as i64) as i32).max(1);
self.ensure_target(sw, sh);
let gl = &self.gl;
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo));
gl.viewport(0, 0, sw, sh);
let l = &self.scene_locs;
gl.use_program(Some(self.scene_prog));
gl.uniform_2_f32(l.res.as_ref(), sw as f32, sh as f32);
gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.uniform_3_f32_slice(l.pal.as_ref(), &f.palette);
gl.uniform_1_f32(l.zoom.as_ref(), f.zoom);
gl.uniform_1_f32(l.bright.as_ref(), f.brightness);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
self.draw_layers(f, sw, sh, true, video_alpha);
let gl = &self.gl;
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
gl.generate_mipmap(glow::TEXTURE_2D);
// Pass 2: the window. Upscaled backdrop, then sharp pictures and video.
gl.bind_framebuffer(
glow::FRAMEBUFFER,
std::num::NonZeroU32::new(saved.framebuffer as u32).map(glow::NativeFramebuffer),
);
gl.viewport(0, 0, w, h);
let l = &self.blit_locs;
gl.use_program(Some(self.blit_prog));
gl.uniform_1_i32(l.scene.as_ref(), 0);
gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
self.draw_layers(f, w, h, false, video_alpha);
// Pass 3: glass, one quad per panel or merged group: dst * a + rgb.
let gl = &self.gl;
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
gl.enable(glow::BLEND);
gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD);
gl.blend_func_separate(glow::ONE, glow::SRC_ALPHA, glow::ZERO, glow::ONE);
let l = &self.glass_locs;
gl.use_program(Some(self.glass_prog));
gl.uniform_1_i32(l.scene.as_ref(), 0);
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
gl.uniform_1_f32(l.scale.as_ref(), f.scale);
gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.uniform_2_f32(l.light.as_ref(), f.light[0], f.light[1]);
let mode = match f.quality {
super::Quality::Full => 0,
super::Quality::Light => 1,
super::Quality::Flat => 2,
};
gl.uniform_1_i32(l.mode.as_ref(), mode);
let rects = &f.rects[..f.rects.len().min(MAX_RECTS)];
let mut rect = [0f32; MAX_GROUP * 4];
let mut param = [0f32; MAX_GROUP * 4];
let mut glow_c = [0f32; MAX_GROUP * 4];
let mut tint = [0f32; MAX_GROUP * 4];
for run in runs(rects) {
let n = run.len();
// Bounds plus room for the shadow (spread + downward offset).
let margin = 132.0 * f.scale;
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
for (i, r) in run.iter().enumerate() {
rect[i * 4..i * 4 + 4].copy_from_slice(&[r.x, r.y, r.w, r.h]);
param[i * 4..i * 4 + 4].copy_from_slice(&[r.radius, r.focus, r.alpha, r.blur]);
glow_c[i * 4..i * 4 + 4].copy_from_slice(&[r.glow[0], r.glow[1], r.glow[2], 0.0]);
tint[i * 4..i * 4 + 4].copy_from_slice(&r.tint);
x0 = x0.min(r.x);
y0 = y0.min(r.y);
x1 = x1.max(r.x + r.w);
y1 = y1.max(r.y + r.h);
}
let bx = [
(x0 - margin).max(0.0),
(y0 - margin).max(0.0),
(x1 + margin).min(w as f32),
(y1 + margin + 46.0 * f.scale).min(h as f32),
];
if bx[0] >= bx[2] || bx[1] >= bx[3] {
continue;
}
gl.uniform_4_f32(l.box_.as_ref(), bx[0], bx[1], bx[2], bx[3]);
gl.uniform_1_i32(l.count.as_ref(), n as i32);
gl.uniform_4_f32_slice(l.rect.as_ref(), &rect[..n * 4]);
gl.uniform_4_f32_slice(l.param.as_ref(), &param[..n * 4]);
gl.uniform_4_f32_slice(l.glow.as_ref(), &glow_c[..n * 4]);
gl.uniform_4_f32_slice(l.tint.as_ref(), &tint[..n * 4]);
gl.draw_arrays(glow::TRIANGLE_STRIP, 0, 4);
}
self.restore(saved);
}
}
/// Reads the current window framebuffer as top-down RGBA8 (dev snapshots).
///
/// # Safety
/// Must be called with the context current, after Slint has rendered.
pub unsafe fn read_pixels(&self, w: u32, h: u32) -> Vec<u8> {
let mut buf = vec![0u8; (w * h * 4) as usize];
unsafe {
self.gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
self.gl.read_pixels(
0,
0,
w as i32,
h as i32,
glow::RGBA,
glow::UNSIGNED_BYTE,
glow::PixelPackData::Slice(Some(&mut buf)),
);
}
let row = (w * 4) as usize;
let mut flipped = Vec::with_capacity(buf.len());
for y in (0..h as usize).rev() {
flipped.extend_from_slice(&buf[y * row..(y + 1) * row]);
}
flipped
}
/// # Safety
/// Must be called with the context current.
pub unsafe fn destroy(&mut self) {
unsafe {
for (_, img) in self.images.drain() {
self.gl.delete_texture(img.tex);
}
if let Some(v) = self.video.take() {
self.gl.delete_texture(v.y);
self.gl.delete_texture(v.uv);
}
self.gl.delete_program(self.scene_prog);
self.gl.delete_program(self.blit_prog);
self.gl.delete_program(self.image_prog);
self.gl.delete_program(self.video_prog);
self.gl.delete_program(self.glass_prog);
self.gl.delete_vertex_array(self.vao);
self.gl.delete_framebuffer(self.fbo);
self.gl.delete_texture(self.tex);
}
}
}
/// Linear filtering on the bound texture, with mipmaps for minification.
unsafe fn set_filter(gl: &glow::Context, mipmaps: bool) {
let min = if mipmaps { glow::LINEAR_MIPMAP_LINEAR } else { glow::LINEAR };
unsafe {
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, min as i32);
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
}
}
/// Splits the panels into draw runs: consecutive panels sharing a group
/// (> 0) melt together and are drawn as one; the rest are drawn alone.
fn runs(rects: &[Panel]) -> impl Iterator<Item = &[Panel]> {
let mut rest = rects;
std::iter::from_fn(move || {
let first = rest.first()?;
let mut n = 1;
if first.group > 0.5 {
while n < rest.len() && n < MAX_GROUP && (rest[n].group - first.group).abs() < 0.5 {
n += 1;
}
}
let (run, tail) = rest.split_at(n);
rest = tail;
Some(run)
})
}
unsafe fn link(gl: &glow::Context, header: &str, vs: &str, fs: &str) -> anyhow::Result<glow::Program> {
unsafe {
let program = gl.create_program().map_err(anyhow::Error::msg)?;
let mut shaders = Vec::new();
for (kind, src) in [(glow::VERTEX_SHADER, vs), (glow::FRAGMENT_SHADER, fs)] {
let sh = gl.create_shader(kind).map_err(anyhow::Error::msg)?;
gl.shader_source(sh, &format!("{header}{src}"));
gl.compile_shader(sh);
if !gl.get_shader_compile_status(sh) {
anyhow::bail!("shader compile failed: {}", gl.get_shader_info_log(sh));
}
gl.attach_shader(program, sh);
shaders.push(sh);
}
gl.link_program(program);
if !gl.get_program_link_status(program) {
anyhow::bail!("program link failed: {}", gl.get_program_info_log(program));
}
for sh in shaders {
gl.detach_shader(program, sh);
gl.delete_shader(sh);
}
Ok(program)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn p(group: f32) -> Panel {
Panel { group, alpha: 1.0, ..Panel::default() }
}
#[test]
fn groups_merge_only_when_consecutive() {
let rects = [p(0.0), p(1.0), p(1.0), p(2.0), p(1.0), p(0.0), p(0.0)];
let sizes: Vec<usize> = runs(&rects).map(<[Panel]>::len).collect();
assert_eq!(sizes, [1, 2, 1, 1, 1, 1]);
let big = [p(3.0); 6];
let sizes: Vec<usize> = runs(&big).map(<[Panel]>::len).collect();
assert_eq!(sizes, [MAX_GROUP, 2]);
}
}

471
sf-ui/src/render/shaders.rs Normal file
View File

@@ -0,0 +1,471 @@
//! GLSL sources. The `#version` line is added at runtime (desktop GL 3.3 core or GLES 3.0).
/// Fullscreen triangle without vertex buffers.
pub const VERTEX: &str = r#"
out vec2 vUv;
void main() {
vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
vUv = p;
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
}
"#;
/// A quad over `uBox` (x0, y0, x1, y1 in px, top-left origin), drawn as a
/// 4-vertex triangle strip. Glass panels only shade the pixels they can reach.
pub const QUAD_VERTEX: &str = r#"
uniform vec4 uBox;
uniform vec2 uRes;
void main() {
vec2 c = vec2(float(gl_VertexID & 1), float((gl_VertexID >> 1) & 1));
vec2 p = mix(uBox.xy, uBox.zw, c);
gl_Position = vec4(p.x / uRes.x * 2.0 - 1.0, 1.0 - p.y / uRes.y * 2.0, 0.0, 1.0);
}
"#;
/// Backdrop: a dark, slowly flowing mesh gradient (soft colour fields in the
/// focused app's palette), like Apple's dark dynamic wallpapers.
///
/// It is smooth by design, so it is rendered at low resolution and upscaled.
/// Cost per pixel: a handful of exp() calls, no noise, no loops over shapes.
pub const SCENE: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform vec2 uRes;
uniform float uTime;
uniform vec3 uPal[3]; // highlight, mid, deep
uniform float uZoom; // launch fly-in
uniform float uBright; // backdrop brightness: 1 = full, lower = calmer (launcher: shelf hidden)
float field(vec2 d, float r) {
return exp(-dot(d, d) / (r * r));
}
// Rotates the hue around the grey axis (keeps brightness roughly the same).
vec3 hueRot(vec3 c, float ang) {
const vec3 k = vec3(0.57735);
float ca = cos(ang);
return max(c * ca + cross(k, c) * sin(ang) + k * dot(k, c) * (1.0 - ca), 0.0);
}
void main() {
vec2 uv = vec2(vUv.x, 1.0 - vUv.y); // top-left origin
uv = (uv - 0.5) / uZoom + 0.5;
float aspect = uRes.x / uRes.y;
float t = uTime;
// Gentle flow: two layers of low-frequency sine warp make the fields drift
// and bend like liquid without any visible shapes.
vec2 w = uv;
w += 0.050 * vec2(sin(uv.y * 3.1 + t * 0.110), sin(uv.x * 2.3 - t * 0.090));
w += 0.022 * vec2(sin(uv.y * 5.7 - t * 0.070 + 1.3), sin(uv.x * 4.9 + t * 0.130 + 0.7));
vec2 a = vec2(aspect, 1.0);
vec3 hi = uPal[0];
vec3 mid = uPal[1];
vec3 deep = uPal[2];
// Near-black base; colour lives in a few soft fields with dark gaps between.
vec3 col = deep * 0.35 + vec3(0.003, 0.003, 0.005);
// Fields on slow Lissajous paths. Two are hue-shifted for depth, like
// Apple's dark gradients (never a single flat hue).
vec2 c0 = vec2(0.76 + 0.10 * sin(t * 0.050), 0.18 + 0.08 * cos(t * 0.043));
vec2 c1 = vec2(0.20 + 0.12 * cos(t * 0.037 + 1.0), 0.26 + 0.10 * sin(t * 0.041));
vec2 c2 = vec2(0.52 + 0.20 * sin(t * 0.029 + 2.0), 0.62 + 0.08 * cos(t * 0.033 + 0.5));
vec2 c3 = vec2(0.96 + 0.05 * cos(t * 0.045), 0.88 + 0.06 * sin(t * 0.052));
vec2 c4 = vec2(0.04 + 0.06 * sin(t * 0.031 + 4.0), 0.94 + 0.05 * cos(t * 0.027));
col += hi * 0.34 * field((w - c0) * a, 0.40);
col += mid * 0.62 * field((w - c1) * a, 0.48);
col += hueRot(mix(mid, hi, 0.4), 0.55) * 0.34 * field((w - c2) * a, 0.38);
col += hueRot(mid, -0.70) * 0.40 * field((w - c3) * a, 0.36);
col += mid * 0.30 * field((w - c4) * a, 0.34);
// Soft shoulder so bright palettes stay "dark mode".
col = col / (1.0 + col * 1.2);
// Calmer at the bottom where the icons sit; dimmer when asked (uBright).
col *= mix(1.0, 0.62, smoothstep(0.45, 1.0, uv.y));
col *= mix(0.42, 1.0, uBright);
vec2 v = uv - 0.5;
col *= 1.0 - 0.30 * dot(v, v);
fragColor = vec4(col, 1.0);
}
"#;
/// Upscales the backdrop to the window with dithering (no banding).
pub const BLIT: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform sampler2D uScene;
uniform float uTime;
float hash12(vec2 p) {
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
void main() {
vec3 col = textureLod(uScene, vUv, 0.0).rgb;
col += (hash12(gl_FragCoord.xy + fract(uTime) * 61.0) - 0.5) / 255.0;
fragColor = vec4(col, 1.0);
}
"#;
/// A backdrop picture (artwork), cover-fitted to the viewport and toned for
/// text on top: darkened overall (`uDim`) and towards the left and bottom
/// edges, where titles usually sit. Blended with alpha (crossfades).
pub const IMAGE: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform sampler2D uImage;
uniform vec2 uImg; // image size, px
uniform vec2 uRes; // viewport size, px
uniform vec2 uAlign; // which part stays visible when cropping (0..1, 0.5 = centre)
uniform float uDim;
uniform float uFadeLeft;
uniform float uFadeBottom;
uniform float uAlpha;
void main() {
vec2 uv = vec2(vUv.x, 1.0 - vUv.y); // top-left origin, like the image rows
float va = uRes.x / uRes.y;
float ia = uImg.x / max(uImg.y, 1.0);
vec2 st = uv;
if (ia > va) {
float f = va / ia;
st.x = uAlign.x * (1.0 - f) + uv.x * f;
} else {
float f = ia / va;
st.y = uAlign.y * (1.0 - f) + uv.y * f;
}
vec3 col = texture(uImage, st).rgb;
float kl = uFadeLeft * (1.0 - smoothstep(0.05, 0.85, uv.x));
float kb = uFadeBottom * smoothstep(0.30, 0.95, uv.y);
float k = 1.0 - (1.0 - kl) * (1.0 - kb);
col = mix(col, vec3(0.018, 0.018, 0.022), k) * (1.0 - uDim);
fragColor = vec4(col, uAlpha);
}
"#;
/// A video frame (NV12: full-size Y plane, half-size interleaved CbCr plane),
/// contain-fitted with black bars, converted to RGB here.
pub const VIDEO: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform sampler2D uY;
uniform sampler2D uUV;
uniform vec2 uRes; // viewport size, px
uniform float uAspect; // display aspect of the video
uniform int uMatrix; // 0 = BT.601, 1 = BT.709, 2 = BT.2020
uniform int uFull; // 1 = full range (0..255), else limited (16..235)
uniform float uAlpha;
void main() {
vec2 uv = vec2(vUv.x, 1.0 - vUv.y);
float va = uRes.x / uRes.y;
vec2 st = uv;
float inside = 1.0;
if (uAspect > va) {
float h = va / uAspect;
st.y = (uv.y - 0.5) / h + 0.5;
} else {
float w = uAspect / va;
st.x = (uv.x - 0.5) / w + 0.5;
}
if (st.x < 0.0 || st.x > 1.0 || st.y < 0.0 || st.y > 1.0) inside = 0.0;
st = clamp(st, vec2(0.0), vec2(1.0));
float y = texture(uY, st).r;
vec2 c = texture(uUV, st).rg;
if (uFull == 1) {
c -= 0.5;
} else {
y = (y - 16.0 / 255.0) * (255.0 / 219.0);
c = (c - 128.0 / 255.0) * (255.0 / 224.0);
}
vec3 rgb;
if (uMatrix == 0) {
rgb = vec3(y + 1.402 * c.y, y - 0.344136 * c.x - 0.714136 * c.y, y + 1.772 * c.x);
} else if (uMatrix == 2) {
rgb = vec3(y + 1.4746 * c.y, y - 0.16455 * c.x - 0.57135 * c.y, y + 1.8814 * c.x);
} else {
rgb = vec3(y + 1.5748 * c.y, y - 0.1873 * c.x - 0.4681 * c.y, y + 1.8556 * c.x);
}
fragColor = vec4(clamp(rgb, 0.0, 1.0) * inside, uAlpha);
}
"#;
/// One Liquid Glass panel (or one merged group of panels), drawn as a quad
/// over its bounds plus the shadow margin.
///
/// The model follows Apple's Liquid Glass: light is *bent*, not scattered.
/// Each panel is a slab of glass (IOR ~1.5) whose edge is a convex squircle
/// bevel. The backdrop seen through it is displaced by a real refraction ray
/// (Snell), with per-channel IOR for dispersion. Bigger panels are thicker:
/// wider bevel, stronger lensing, deeper shadow. On top: Fresnel reflection,
/// a geometry-aware specular rim, light from within when focused, and
/// "materialize" (alpha ramps the lensing, not just the opacity).
///
/// The result is written as `dst * a + rgb` (blend ONE, SRC_ALPHA), so the
/// shader never needs to read the framebuffer: shadows multiply, glass
/// replaces, and nested glass (on another pane) lights what is already there.
pub const GLASS: &str = r#"
out vec4 fragColor;
#define MAX_GROUP 4
uniform sampler2D uScene;
uniform vec2 uRes; // physical px
uniform float uScale; // physical px per design px
uniform float uTime;
uniform vec2 uLight; // direction towards the key light (screen space, y down)
uniform int uCount; // members of this run (> 1 = merged group)
uniform vec4 uRect[MAX_GROUP]; // x, y, w, h (px, top-left origin)
uniform vec4 uParam[MAX_GROUP]; // radius, focus, alpha, frost (mip lod; < 0 = nested on other glass)
uniform vec4 uGlow[MAX_GROUP]; // accent rgb, unused
uniform vec4 uTint[MAX_GROUP]; // tint rgb, tint amount
uniform int uMode; // 0 = full, 1 = light (frost, no lensing), 2 = flat (no frost)
float sdRoundRect(vec2 p, vec2 b, float r) {
vec2 q = abs(p) - b + r;
return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
}
// Analytic outward gradient of sdRoundRect.
vec2 gradRoundRect(vec2 p, vec2 b, float r) {
vec2 w = abs(p) - b + r;
vec2 q = max(w, 0.0);
vec2 g = (max(w.x, w.y) > 0.0) ? q / max(length(q), 1e-5) : ((w.x > w.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0));
return sign(p) * g;
}
float sdPanel(int i, vec2 p) {
vec4 R = uRect[i];
vec2 hs = R.zw * 0.5;
float r = min(uParam[i].x, min(hs.x, hs.y));
return sdRoundRect(p - (R.xy + hs), hs, r);
}
// Polynomial smooth minimum: the "liquid bridge" between merged panels.
float smin(float a, float b, float k) {
float h = max(k - abs(a - b), 0.0) / k;
return min(a, b) - h * h * k * 0.25;
}
float sdGroup(vec2 p, float k) {
float d = 1e5;
for (int i = 0; i < MAX_GROUP; i++) {
if (i >= uCount) break;
if (uParam[i].z <= 0.001) continue;
d = smin(d, sdPanel(i, p), k);
}
return d;
}
// uv has a top-left origin; the scene texture is stored GL-style (bottom row first).
vec3 sceneAt(vec2 uv, float lod) {
uv = clamp(uv, vec2(0.001), vec2(0.999));
return textureLod(uScene, vec2(uv.x, 1.0 - uv.y), lod).rgb;
}
float luma(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
// Convex squircle bevel: height (0 at the rim, 1 on the flat top) and slope.
// u = distance from the rim / bevel width.
vec2 squircle(float u) {
u = clamp(u, 0.0, 1.0);
float a = 1.0 - u;
float a4 = a * a * a * a;
float h = pow(max(1.0 - a4, 1e-4), 0.25);
float dh = a * a * a * pow(max(1.0 - a4, 1e-3), -0.75);
return vec2(h, dh);
}
// Where a vertical ray through the glass lands on the backdrop (px offset).
vec2 refractOffset(vec3 N, float height, float ior) {
vec3 t = refract(vec3(0.0, 0.0, -1.0), N, 1.0 / ior);
return t.xy / max(-t.z, 0.2) * height;
}
void main() {
vec2 p = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y); // px, top-left
float s = uScale;
float mergeK = 30.0 * s;
bool merged = uCount > 1;
// Combined distance, and parameters blended towards the nearest member.
float d = 1e5;
float wsum = 0.0;
vec4 P = vec4(0.0);
vec3 accent = vec3(0.0);
vec4 tint = vec4(0.0);
vec2 center = vec2(0.0);
vec2 halfSize = vec2(0.0);
for (int k = 0; k < MAX_GROUP; k++) {
if (k >= uCount) break;
float a = uParam[k].z;
if (a <= 0.001) continue;
float dk = sdPanel(k, p);
d = merged ? smin(d, dk, mergeK) : dk;
float w = exp(-max(dk, 0.0) / (12.0 * s)) + 1e-4;
wsum += w;
P += uParam[k] * w;
accent += uGlow[k].rgb * w;
tint += uTint[k] * w;
vec4 R = uRect[k];
center += (R.xy + R.zw * 0.5) * w;
halfSize += R.zw * 0.5 * w;
}
if (wsum <= 0.0) discard;
P /= wsum; accent /= wsum; tint /= wsum; center /= wsum; halfSize /= wsum;
float focus = P.y;
float alpha = P.z;
float minHalf = min(halfSize.x, halfSize.y);
bool nested = P.w < 0.0;
// Size-dependent thickness: small controls are full domes (a drop of
// liquid), big panes are thick slabs with a wide rounded edge.
float bezel = min(minHalf * 0.80, 9.0 * s + minHalf * 0.10);
bezel = clamp(bezel, 5.0 * s, 40.0 * s);
float sizeK = clamp(minHalf / (240.0 * s), 0.0, 1.0);
float small = 1.0 - clamp(minHalf / (90.0 * s), 0.0, 1.0);
// Output is dst * mul + add.
float mul = 1.0;
vec3 add = vec3(0.0);
// ---- outside: grounding shadow and a little accent light spill ----
if (d > 0.0) {
vec2 off = vec2(0.0, (10.0 + 18.0 * focus + 14.0 * sizeK) * s);
float ds = merged ? sdGroup(p - off, mergeK) : sdPanel(0, p - off);
float spread = (34.0 + 34.0 * focus + 50.0 * sizeK) * s * (nested ? 0.5 : 1.0);
float shadow = (1.0 - smoothstep(-spread * 0.5, spread, ds)) * (0.26 + 0.22 * focus + 0.18 * sizeK);
shadow += (1.0 - smoothstep(0.0, 6.0 * s, d)) * 0.10;
mul = 1.0 - shadow * alpha;
add = accent * exp(-d / (22.0 * s)) * focus * 0.16 * alpha;
if (d > 1.0) {
if (mul > 0.998 && dot(add, vec3(1.0)) < 0.002) discard;
fragColor = vec4(add, mul);
return;
}
}
// ---- surface geometry ----
vec2 n2;
if (merged) {
vec2 e = vec2(0.75, 0.0);
vec2 g2 = vec2(sdGroup(p + e.xy, mergeK) - sdGroup(p - e.xy, mergeK),
sdGroup(p + e.yx, mergeK) - sdGroup(p - e.yx, mergeK));
n2 = g2 / max(length(g2), 1e-5);
} else {
vec4 R = uRect[0];
vec2 hs = R.zw * 0.5;
n2 = gradRoundRect(p - (R.xy + hs), hs, min(uParam[0].x, min(hs.x, hs.y)));
}
float inside = max(-d, 0.0);
float u = inside / bezel;
vec2 hp = squircle(u);
float thick = bezel * (1.1 + 0.3 * focus); // glass height in px
float height = thick * hp.x;
float slope = (u < 1.0) ? hp.y * thick / bezel : 0.0;
slope = min(slope, 6.0);
vec3 N = normalize(vec3(n2 * slope, 1.0));
// Materialize: lensing and frost ramp up with alpha instead of a plain fade.
float mat = smoothstep(0.0, 1.0, alpha);
float lens = (1.25 + 0.35 * focus) * mat;
vec2 mag = -(p - center) * (0.025 + 0.035 * focus) * mat;
float lod = abs(P.w) * mix(0.35, 1.0, mat);
// The glass colour is affine in what is underneath: g = dst * A + B.
float A = 0.0;
vec3 B;
if (nested || uMode == 2) {
A = 1.0;
B = vec3(0.0);
} else if (uMode == 1) {
B = sceneAt(p / uRes, lod);
} else if (slope > 0.02) {
// Bevel: refract each channel with its own IOR (dispersion).
B.r = sceneAt((p + refractOffset(N, height, 1.46) * lens + mag) / uRes, lod).r;
B.g = sceneAt((p + refractOffset(N, height, 1.50) * lens + mag) / uRes, lod).g;
B.b = sceneAt((p + refractOffset(N, height, 1.56) * lens + mag) / uRes, lod).b;
} else {
B = sceneAt((p + mag) / uRes, lod);
}
// ---- body ----
// Adaptive tone: lift glass over dark content, hold it back over bright content.
float bgL = luma(sceneAt(center / uRes, 6.0));
float kb = 1.02 + 0.10 * focus;
A *= kb;
B = B * kb + mix(0.045, -0.01, clamp(bgL * 2.0, 0.0, 1.0)) + (nested ? 0.025 : 0.0);
A *= 1.0 - tint.a;
B = mix(B, tint.rgb, tint.a);
// Light from within when focused: starts at the center, spreads to the rim.
vec2 qn = (p - center) / max(halfSize, vec2(1.0));
float core = exp(-dot(qn, qn) * 1.3);
vec3 inner = mix(vec3(1.0), accent, 0.45);
B += inner * focus * (0.06 + 0.12 * core);
// Focus sheen: a soft diagonal band of light glides across the glass now and then.
float sweep = fract(uTime * 0.16 + center.x * 0.0007);
float band = (qn.x * 0.8 + qn.y * 0.45) * 0.5 + 0.5;
float sheen = exp(-pow((band - (sweep * 1.8 - 0.4)) * 7.0, 2.0));
B += vec3(1.0) * sheen * focus * 0.10 * mat;
// Soft vertical sheen, as if lit from above.
float vy = clamp((p.y - (center.y - halfSize.y)) / (2.0 * halfSize.y), 0.0, 1.0);
B += vec3(0.06 + 0.05 * focus) * pow(1.0 - vy, 2.5);
// ---- light ----
float wob = focus * 0.35 * sin(uTime * 0.9);
vec2 L2 = mat2(cos(wob), sin(wob), -sin(wob), cos(wob)) * uLight;
vec3 L = normalize(vec3(L2, 0.55));
vec3 V = vec3(0.0, 0.0, 1.0);
// Fresnel: steep bevel reflects the (blurred, brightened) surroundings.
float cosT = clamp(N.z, 0.0, 1.0);
float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0);
float Fm = uMode == 0 ? clamp(F, 0.0, 1.0) * 0.35 * mat : 0.0;
vec3 env = mix(sceneAt((p + n2 * 60.0 * s) / uRes, 5.0) * 1.6, vec3(0.92), 0.35);
A *= 1.0 - Fm;
B = mix(B, env, Fm);
// Specular on the bevel: key light, plus a weaker bounce on the far side.
vec3 H = normalize(L + V);
vec3 H2 = normalize(vec3(-L2, 0.55) + V);
float spec = pow(max(dot(N, H), 0.0), 26.0);
float spec2 = pow(max(dot(N, H2), 0.0), 26.0);
float bevelMask = 1.0 - smoothstep(0.0, 1.0, u);
B += vec3(1.0) * (spec * 0.60 + spec2 * 0.38) * bevelMask * (0.8 + 0.6 * focus) * mat;
// Glossy highlight on small domes, like a water drop.
vec2 hl = qn - uLight * 0.42;
float gloss = exp(-dot(hl * vec2(1.4, 2.2), hl * vec2(1.4, 2.2)) * 3.0);
B += vec3(1.0) * gloss * small * 0.14 * mat;
// Crisp rim: a bright hairline all around, strongest towards the light
// and again on the far side where light exits the glass.
float facing = max(dot(n2, uLight), 0.0);
float away = max(dot(n2, -uLight), 0.0);
float rimLine = exp(-inside / (1.0 * s));
float rimGlow = exp(-inside / (6.0 * s));
B += rimLine * (0.22 + 0.80 * pow(facing, 2.0) + 0.55 * pow(away, 2.0) + 0.22 * focus) * mat;
B += rimGlow * (0.06 + 0.10 * facing + 0.06 * away + 0.08 * focus) * mat;
B += accent * rimGlow * focus * 0.10 * mat;
// Subtle inner shade on the side away from the light gives the slab depth.
float shade = 1.0 - 0.08 * bevelMask * away * mat;
A *= shade;
B *= shade;
float cov = clamp(0.5 - d, 0.0, 1.0) * clamp(alpha * 2.0, 0.0, 1.0);
float keep = 1.0 - cov + cov * A;
fragColor = vec4(add * keep + cov * B, mul * keep);
}
"#;

39
sf-ui/src/text.rs Normal file
View File

@@ -0,0 +1,39 @@
//! String helpers Slint lacks (wired into the `SfText` global by `glue!`).
/// Without its last character.
pub fn drop_last(s: &str) -> String {
let mut s = s.to_string();
s.pop();
s
}
/// `n` bullets (a masked password).
pub fn dots(n: usize) -> String {
"•".repeat(n)
}
/// The characters of a key event's text that can be typed: no controls, no
/// Slint special keys (arrows etc. arrive as private-use code points).
pub fn typable(s: &str) -> String {
s.chars().filter(|c| !c.is_control() && !('\u{E000}'..='\u{F8FF}').contains(c)).collect()
}
/// At most `n` characters.
pub fn truncate(s: &str, n: usize) -> String {
s.chars().take(n).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn edits() {
assert_eq!(drop_last("abő"), "ab");
assert_eq!(drop_last(""), "");
assert_eq!(dots(3), "•••");
assert_eq!(truncate("árvíz", 3), "árv");
assert_eq!(typable("a\u{F700}\n"), "a");
assert_eq!(typable("Ő"), "Ő");
}
}

483
sf-ui/src/video.rs Normal file
View File

@@ -0,0 +1,483 @@
//! Video playback with GStreamer, shown through the glass layer: the film is
//! the backdrop, so glass controls on top refract it.
//!
//! - Hardware decoding (VA-API: H.264, HEVC incl. 10-bit, VP9, AV1) when the
//! app has the `gpu` permission; FFmpeg software decoders otherwise.
//! - `vapostproc` converts on the GPU and tone-maps HDR to SDR.
//! - Every audio and subtitle track of the file (MKV, MP4, TS...), with
//! embedded ASS/SRT subtitles rendered by GStreamer.
//! - HTTP(S) streams with range seeking (a server streaming a file while it
//! downloads works).
//!
//! ```ignore
//! sf_ui::video::init()?;
//! let player = Player::new("https://example.com/film.mkv", PlayerOptions { start: 754.0, ..Default::default() })?;
//! glass.set_video(Some(player.video()));
//! // every ~100 ms on the UI thread (slint::Timer):
//! for event in player.poll() { /* Ready, Buffering, Eos, Error... */ }
//! ```
//!
//! Needs GStreamer 1.22+ on the system (the SmartFox TV has it): base, good,
//! bad (va, assrender), libav, and pipewire for sound. Apps need the `gpu`
//! and `audio` permissions, and `network` for streams.
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result};
use gstreamer as gst;
use gstreamer::glib;
use gstreamer::prelude::*;
use gstreamer_app as gst_app;
use gstreamer_video as gst_video;
use gstreamer_video::prelude::*;
use crate::glass::VideoSource;
use crate::render::{Matrix, Nv12Frame};
/// VA-API decoders, preferred over the software ones when present.
const HW_DECODERS: [&str; 6] = ["vah264dec", "vah265dec", "vavp9dec", "vaav1dec", "vavp8dec", "vampeg2dec"];
/// Initialises GStreamer once and ranks the hardware decoders first.
pub fn init() -> Result<()> {
gst::init().context("initialising GStreamer")?;
let registry = gst::Registry::get();
for name in HW_DECODERS {
if let Some(feature) = registry.lookup_feature(name) {
feature.set_rank(gst::Rank::PRIMARY + 1);
}
}
Ok(())
}
/// Whether hardware video decoding is available (diagnostics).
pub fn hardware_decoding() -> bool {
let registry = gst::Registry::get();
HW_DECODERS.iter().any(|n| registry.lookup_feature(n).is_some())
}
#[derive(Debug, Clone)]
pub struct PlayerOptions {
/// Start position in seconds.
pub start: f64,
/// Audio sync correction in milliseconds (positive: audio later).
pub audio_offset_ms: i64,
/// Show subtitles (the default track, see [`Player::set_text`]).
pub subtitles: bool,
/// HTTP user agent for streams.
pub user_agent: Option<String>,
/// Pango font for text subtitles (scaled with the video).
pub subtitle_font: String,
}
impl Default for PlayerOptions {
fn default() -> Self {
PlayerOptions {
start: 0.0,
audio_offset_ms: 0,
subtitles: true,
user_agent: None,
subtitle_font: "Sans Bold 20".into(),
}
}
}
/// What happened since the last [`Player::poll`].
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
/// The stream is open (first frame ready): duration (s, if known) and
/// the tracks can be read now. Playback starts right after.
Ready { duration: Option<f64> },
/// Network buffering, percent (100 = done; playback pauses meanwhile).
Buffering(i32),
/// Playing or paused (as asked, or because of buffering).
Playing(bool),
/// A seek finished.
Seeked,
/// The end of the stream.
Eos,
/// A fatal error; the player stops.
Error(String),
}
/// One audio or subtitle track of the stream.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Track {
/// Index for [`Player::set_audio`] / [`Player::set_text`].
pub index: i32,
/// ISO 639 code ("hu", "en", "hun"...), if tagged.
pub language: Option<String>,
/// The track's title in the file ("Commentary", "Forced"...).
pub title: Option<String>,
pub codec: Option<String>,
}
/// The newest decoded frame, shared with the appsink thread.
#[derive(Default)]
struct Feed {
latest: Mutex<Option<gst::Sample>>,
}
struct FeedSource(Arc<Feed>);
struct GstFrame {
frame: gst_video::VideoFrame<gst_video::video_frame::Readable>,
aspect: f32,
matrix: Matrix,
full: bool,
}
impl Nv12Frame for GstFrame {
fn width(&self) -> u32 {
self.frame.width()
}
fn height(&self) -> u32 {
self.frame.height()
}
fn aspect(&self) -> f32 {
self.aspect
}
fn plane(&self, index: usize) -> (&[u8], usize) {
let data = self.frame.plane_data(index as u32).unwrap_or(&[]);
let stride = self.frame.plane_stride().get(index).copied().unwrap_or(0).max(0) as usize;
(data, stride)
}
fn matrix(&self) -> Matrix {
self.matrix
}
fn full_range(&self) -> bool {
self.full
}
}
impl VideoSource for FeedSource {
fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>> {
let sample = self.0.latest.lock().unwrap().take()?;
let info = gst_video::VideoInfo::from_caps(sample.caps()?).ok()?;
if info.format() != gst_video::VideoFormat::Nv12 {
return None;
}
let par = info.par();
let aspect = info.width() as f32 * par.numer() as f32 / (info.height().max(1) as f32 * par.denom().max(1) as f32);
let colorimetry = info.colorimetry();
let matrix = match colorimetry.matrix() {
gst_video::VideoColorMatrix::Bt601 | gst_video::VideoColorMatrix::Smpte240m => Matrix::Bt601,
gst_video::VideoColorMatrix::Bt2020 => Matrix::Bt2020,
gst_video::VideoColorMatrix::Bt709 => Matrix::Bt709,
_ if info.height() < 720 => Matrix::Bt601,
_ => Matrix::Bt709,
};
let full = colorimetry.range() == gst_video::VideoColorRange::Range0_255;
let buffer = sample.buffer_owned()?;
let frame = gst_video::VideoFrame::from_buffer_readable(buffer, &info).ok()?;
Some(Box::new(GstFrame { frame, aspect, matrix, full }))
}
}
/// A playing stream. Dropping it stops playback.
pub struct Player {
playbin: gst::Element,
bus: gst::Bus,
feed: Arc<Feed>,
start: f64,
/// Playing was asked for (buffering may hold it paused).
want_playing: bool,
buffering: bool,
ready: bool,
seeking: bool,
failed: bool,
}
impl Player {
/// Opens `uri` (https://, http://, file://) and starts playing as soon
/// as it can. Call [`init`] once before.
pub fn new(uri: &str, opts: PlayerOptions) -> Result<Player> {
let feed = Arc::new(Feed::default());
let caps = gst_video::VideoCapsBuilder::new().format(gst_video::VideoFormat::Nv12).build();
let sink = gst_app::AppSink::builder().caps(&caps).sync(true).max_buffers(2).drop(true).build();
sink.set_property("enable-last-sample", false);
let shared = feed.clone();
sink.set_callbacks(
gst_app::AppSinkCallbacks::builder()
.new_sample(move |s| {
let sample = s.pull_sample().map_err(|_| gst::FlowError::Eos)?;
*shared.latest.lock().unwrap() = Some(sample);
Ok(gst::FlowSuccess::Ok)
})
.build(),
);
let playbin = gst::ElementFactory::make("playbin")
.property("uri", uri)
.property("video-sink", &sink)
.build()
.context("GStreamer playbin is missing (gstreamer1.0-plugins-base)")?;
// GPU colour conversion and HDR tone mapping, before the subtitle
// overlay (which needs system memory) and the sink.
if gst::ElementFactory::find("vapostproc").is_some() {
match gst::parse::bin_from_description("vapostproc name=pp ! video/x-raw,format=NV12", true) {
Ok(bin) => {
if let Some(pp) = bin.by_name("pp") {
if pp.find_property("hdr-tone-mapping").is_some() {
pp.set_property("hdr-tone-mapping", true);
}
}
playbin.set_property("video-filter", &bin);
}
Err(e) => log::warn!("video: vapostproc: {e}"),
}
}
if let Some(audio) = ["pulsesink", "pipewiresink"]
.iter()
.find_map(|n| gst::ElementFactory::make(n).build().ok())
{
playbin.set_property("audio-sink", &audio);
}
playbin.set_property("subtitle-font-desc", opts.subtitle_font.as_str());
playbin.set_property("av-offset", opts.audio_offset_ms * 1_000_000);
// A few seconds of network buffer: smooth over a torrent that delivers in bursts.
playbin.set_property("buffer-duration", 8i64 * 1_000_000_000);
if !opts.subtitles {
set_flag(&playbin, "text", false);
}
if let Some(ua) = opts.user_agent.clone() {
playbin.connect("source-setup", false, move |args| {
if let Some(src) = args.get(1).and_then(|v| v.get::<gst::Element>().ok()) {
if src.find_property("user-agent").is_some() {
src.set_property("user-agent", ua.as_str());
}
}
None
});
}
let bus = playbin.bus().context("playbin has no bus")?;
playbin.set_state(gst::State::Paused).context("opening the stream")?;
Ok(Player {
playbin,
bus,
feed,
start: opts.start.max(0.0),
want_playing: true,
buffering: false,
ready: false,
seeking: false,
failed: false,
})
}
/// The frame source for [`crate::Glass::set_video`].
pub fn video(&self) -> Rc<dyn VideoSource> {
Rc::new(FeedSource(self.feed.clone()))
}
/// Handles what GStreamer reported since the last call. Call it often
/// (every 50–200 ms) on the UI thread; it also drives buffering and the
/// start position.
pub fn poll(&mut self) -> Vec<Event> {
let mut out = Vec::new();
while let Some(msg) = self.bus.pop() {
use gst::MessageView;
match msg.view() {
MessageView::Eos(_) => out.push(Event::Eos),
MessageView::Error(e) => {
let text = match e.debug() {
Some(d) => format!("{} ({d})", e.error()),
None => e.error().to_string(),
};
log::warn!("video: {text}");
self.failed = true;
let _ = self.playbin.set_state(gst::State::Null);
out.push(Event::Error(e.error().to_string()));
}
MessageView::Buffering(b) => {
let pct = b.percent();
out.push(Event::Buffering(pct));
if pct < 100 && !self.buffering {
self.buffering = true;
if self.ready && self.want_playing {
let _ = self.playbin.set_state(gst::State::Paused);
}
} else if pct >= 100 && self.buffering {
self.buffering = false;
if self.ready && self.want_playing {
let _ = self.playbin.set_state(gst::State::Playing);
}
}
}
MessageView::AsyncDone(_) => {
if !self.ready {
if self.start > 0.5 {
// First preroll: jump to the start position, then play.
let at = gst::ClockTime::from_nseconds((self.start * 1e9) as u64);
self.start = 0.0;
if self.playbin.seek_simple(gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT, at).is_ok() {
continue;
}
}
self.ready = true;
out.push(Event::Ready { duration: self.duration() });
if self.want_playing && !self.buffering {
let _ = self.playbin.set_state(gst::State::Playing);
}
} else if self.seeking {
self.seeking = false;
out.push(Event::Seeked);
}
}
MessageView::StateChanged(s) => {
if s.src().is_some_and(|src| src == &self.playbin) {
match s.current() {
gst::State::Playing => out.push(Event::Playing(true)),
gst::State::Paused if s.old() == gst::State::Playing => out.push(Event::Playing(false)),
_ => {}
}
}
}
_ => {}
}
}
out
}
pub fn play(&mut self) {
self.want_playing = true;
if self.ready && !self.buffering && !self.failed {
let _ = self.playbin.set_state(gst::State::Playing);
}
}
pub fn pause(&mut self) {
self.want_playing = false;
if !self.failed {
let _ = self.playbin.set_state(gst::State::Paused);
}
}
/// Play/pause; returns whether it plays now.
pub fn toggle(&mut self) -> bool {
if self.want_playing {
self.pause();
} else {
self.play();
}
self.want_playing
}
/// Playing was asked for (it may still wait for the network).
pub fn is_playing(&self) -> bool {
self.want_playing
}
pub fn is_ready(&self) -> bool {
self.ready
}
pub fn is_buffering(&self) -> bool {
self.buffering || self.seeking || !self.ready
}
/// Current position in seconds.
pub fn position(&self) -> Option<f64> {
self.playbin.query_position::<gst::ClockTime>().map(|t| t.nseconds() as f64 / 1e9)
}
/// Duration in seconds, when the stream knows it.
pub fn duration(&self) -> Option<f64> {
self.playbin.query_duration::<gst::ClockTime>().map(|t| t.nseconds() as f64 / 1e9).filter(|d| *d > 0.0)
}
/// Jumps to `seconds`. `exact` decodes up to that very frame (slower);
/// otherwise it lands on the nearest keyframe before it.
pub fn seek(&mut self, seconds: f64, exact: bool) {
if !self.ready {
self.start = seconds.max(0.0);
return;
}
let flags = gst::SeekFlags::FLUSH | if exact { gst::SeekFlags::ACCURATE } else { gst::SeekFlags::KEY_UNIT };
let at = gst::ClockTime::from_nseconds((seconds.max(0.0) * 1e9) as u64);
if self.playbin.seek_simple(flags, at).is_ok() {
self.seeking = true;
}
}
pub fn audio_tracks(&self) -> Vec<Track> {
self.tracks("n-audio", "get-audio-tags", gst::tags::AudioCodec::TAG_NAME)
}
pub fn text_tracks(&self) -> Vec<Track> {
self.tracks("n-text", "get-text-tags", gst::tags::SubtitleCodec::TAG_NAME)
}
pub fn current_audio(&self) -> i32 {
self.playbin.property::<i32>("current-audio")
}
/// The subtitle track shown, or `None` when subtitles are off.
pub fn current_text(&self) -> Option<i32> {
get_flag(&self.playbin, "text").then(|| self.playbin.property::<i32>("current-text")).filter(|i| *i >= 0)
}
pub fn set_audio(&self, index: i32) {
self.playbin.set_property("current-audio", index);
}
/// Shows subtitle track `index`, or hides subtitles (`None`).
pub fn set_text(&self, index: Option<i32>) {
match index {
Some(i) => {
set_flag(&self.playbin, "text", true);
self.playbin.set_property("current-text", i);
}
None => set_flag(&self.playbin, "text", false),
}
}
/// Audio sync correction in milliseconds (positive: audio later).
pub fn set_audio_offset_ms(&self, ms: i64) {
self.playbin.set_property("av-offset", ms * 1_000_000);
}
fn tracks(&self, count: &str, signal: &str, codec_tag: &str) -> Vec<Track> {
let n = self.playbin.property::<i32>(count);
(0..n)
.map(|i| {
let tags = self.playbin.emit_by_name::<Option<gst::TagList>>(signal, &[&i]);
let mut t = Track { index: i, ..Track::default() };
if let Some(tags) = tags {
t.language = tags.get::<gst::tags::LanguageCode>().map(|v| v.get().to_string());
t.title = tags.get::<gst::tags::Title>().map(|v| v.get().to_string());
t.codec = tags
.generic(codec_tag)
.and_then(|v| v.get::<String>().ok())
.or_else(|| tags.get::<gst::tags::Codec>().map(|v| v.get().to_string()));
}
t
})
.collect()
}
}
impl Drop for Player {
fn drop(&mut self) {
let _ = self.playbin.set_state(gst::State::Null);
}
}
fn get_flag(playbin: &gst::Element, nick: &str) -> bool {
let value = playbin.property_value("flags");
let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return false };
class.value_by_nick(nick).is_some_and(|f| class.is_set(&value, f.value()))
}
fn set_flag(playbin: &gst::Element, nick: &str, on: bool) {
let value = playbin.property_value("flags");
let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return };
let Some(builder) = class.builder_with_value(value) else { return };
let builder = if on { builder.set_by_nick(nick) } else { builder.unset_by_nick(nick) };
if let Some(v) = builder.build() {
playbin.set_property_from_value("flags", &v);
}
}