Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb6b6fa9e3 | ||
|
|
9646eef487 | ||
|
|
6f67ddb709 | ||
|
|
2cbc35f181 | ||
|
|
4f66ddb515 | ||
|
|
b14972f657 | ||
|
|
77eb2c2d33 | ||
|
|
4f58edf436 | ||
|
|
01b20165cc | ||
|
|
4b2802076b | ||
|
|
943ff7c15f | ||
|
|
f13a127c9d | ||
|
|
a0ac4f2d35 | ||
|
|
b8419778a5 | ||
|
|
08b6aa0139 | ||
|
|
87263489c0 | ||
|
|
f2cb516e8a | ||
|
|
b25e639a1c | ||
|
|
01fe14f197 | ||
|
|
3b39e80e40 | ||
|
|
0e3c437d50 | ||
|
|
76e7963f03 | ||
|
|
597697d0a6 | ||
|
|
0c59ed8b4b | ||
|
|
79f063d00c | ||
|
|
5ee2df5db7 | ||
|
|
da0b39fef0 | ||
|
|
fd582828c2 | ||
|
|
58a3c829d7 | ||
|
|
9717289271 | ||
|
|
b301c63387 | ||
|
|
1fa4d744be | ||
|
|
5869e3ced1 | ||
|
|
69939c066d | ||
|
|
5bc117c518 | ||
|
|
fffcf0679c | ||
|
|
02566d571b | ||
|
|
701b57bfe8 | ||
|
|
ca9a70e10a | ||
|
|
bb3369b709 | ||
|
|
33dec6f327 | ||
|
|
41e4f3b12b | ||
|
|
28b14b2ad0 | ||
|
|
7c2ac0e4d8 | ||
|
|
83410bd4b4 | ||
|
|
6c8cb5b9e0 | ||
|
|
b76eefb404 | ||
|
|
ff490ab9ae | ||
|
|
6348e57de0 | ||
|
|
1c537d99da | ||
|
|
1848c920d9 | ||
|
|
863edc80fc | ||
|
|
7909b51df1 | ||
|
|
ca612d7807 | ||
|
|
255e16434e | ||
|
|
9411145ce9 | ||
|
|
f1fba186c1 | ||
|
|
aa7d3a3bf4 | ||
|
|
7525a604f2 |
@@ -1,3 +1,27 @@
|
||||
# 1.0.7-alpha:
|
||||
Changes:
|
||||
- HDR video support: PQ/HLG/BT.2020 video is now read correctly (decoded to scene-linear), with a per-document output mode (clip vs highlight rolloff) and 10-bit HDR export (HEVC Main10, PQ or HLG)
|
||||
- Hardware-accelerated video decode (VAAPI) for both playback and export, including a GPU NV12 preview path; the editor now runs on a shared VAAPI-capable GPU device so decode → composite → encode stay GPU-resident
|
||||
- SVG import and export for vector layers: export the current frame to .svg, and import .svg as a new vector layer (Ctrl+I)
|
||||
- Export fit modes: choose Stretch, Letterbox, or Crop when the export resolution's aspect ratio differs from the document (video and image export)
|
||||
- Videos imported directly and dragged in from the asset library now use the same placement, so they no longer end up with different aspect ratios
|
||||
- Resizing the document now leaves raster layers untouched; the Info Panel shows the active raster layer's size and a "Layer to document size" button (scale or expand/crop)
|
||||
- The active raster layer now shows a dashed outline on the canvas
|
||||
- H.264 export gained a color-range option (Limited/TV or Full/PC)
|
||||
- Hide/Show Layer now works
|
||||
|
||||
Bugfixes:
|
||||
- Fix sped-up and jerky 4K video playback (frame-index frame cache + request-based seeking)
|
||||
- Fix washed-out HDR/10-bit video (propagate stream color tags to hardware frames, P010 import)
|
||||
- Fix the final frame(s) of a clip occasionally failing to render at the end of the stream
|
||||
- Fix the CPU export color path producing shifted colors on unusual resolutions (BT.709 + honor the chosen range)
|
||||
- Fix fills occasionally vanishing after a paint-bucket or lasso cut
|
||||
- Fix silent gaps in exported audio
|
||||
- Fix black video thumbnails and decoder thrashing
|
||||
- Fix file-descriptor and GPU-memory leaks on hardware-import error paths
|
||||
- SVG export now omits hidden layers; SVG import respects gradient opacity
|
||||
- Fix the macOS/Windows build (hardware export is Linux-only)
|
||||
|
||||
# 1.0.6-alpha:
|
||||
Changes:
|
||||
- Hardware-accelerated H.264 video export: each frame is rendered and encoded on the GPU (zero-copy VAAPI), roughly 2x faster, with automatic fallback to software encoding when hardware acceleration isn't available (Linux, Intel/AMD only for now)
|
||||
|
||||
@@ -164,11 +164,11 @@ impl AudioNode for OscillatorNode {
|
||||
output[frame * 2] = sample; // Left
|
||||
output[frame * 2 + 1] = sample; // Right
|
||||
|
||||
// Update phase once per frame
|
||||
self.phase += freq_mod / sample_rate_f32;
|
||||
if self.phase >= 1.0 {
|
||||
self.phase -= 1.0;
|
||||
}
|
||||
// Update phase once per frame. `rem_euclid(1.0)` gives a numerically stable
|
||||
// wraparound into [0, 1): repeated conditional subtraction accumulates f32
|
||||
// rounding error over long-held notes (timbre drift), and FM can drive
|
||||
// `freq_mod` negative, which a one-sided `if >= 1.0` wouldn't wrap at all.
|
||||
self.phase = (self.phase + freq_mod / sample_rate_f32).rem_euclid(1.0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -582,8 +582,21 @@ impl AudioClipPool {
|
||||
// or a container without exact stream duration). They will never
|
||||
// arrive — stop waiting and let the render fill silence, instead of
|
||||
// burning the 10s safety valve on every remaining chunk.
|
||||
//
|
||||
// BUT `finished` may be stale: we just moved the target with
|
||||
// `set_target_frame`, and on a forward jump past the buffer the reader
|
||||
// will reset()+seek() (clearing `finished`) on its next poll. The reader
|
||||
// re-seeks when `target < buf_start || target > buf_end + sample_rate`
|
||||
// (see disk_reader.rs), so only trust EOF when the target is inside the
|
||||
// current window — otherwise a stale flag from the previous region would
|
||||
// make us render silence over audio that's about to be decoded.
|
||||
if ra.is_finished() {
|
||||
break;
|
||||
let (buf_start, buf_end) = ra.snapshot();
|
||||
let sr = audio_file.sample_rate as u64;
|
||||
let seek_pending = src_start < buf_start || src_start > buf_end + sr;
|
||||
if !seek_pending {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_micros(100));
|
||||
wait_iters += 1;
|
||||
|
||||
@@ -113,11 +113,10 @@ impl SynthVoice {
|
||||
// Simple sine wave
|
||||
let sample = (self.phase * 2.0 * PI).sin() * (self.velocity as f32 / 127.0) * 0.3;
|
||||
|
||||
// Update phase
|
||||
self.phase += self.frequency / sample_rate;
|
||||
if self.phase >= 1.0 {
|
||||
self.phase -= 1.0;
|
||||
}
|
||||
// Update phase. Use `.fract()` for a numerically stable wraparound: repeated
|
||||
// conditional subtraction accumulates f32 rounding error over long-held notes,
|
||||
// which drifts the timbre.
|
||||
self.phase = (self.phase + self.frequency / sample_rate).fract();
|
||||
|
||||
self.age += 1;
|
||||
|
||||
|
||||
@@ -15,3 +15,8 @@
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Local, machine-specific cargo config (e.g. PKG_CONFIG_PATH for a local ffmpeg).
|
||||
# CI/packaging build ffmpeg from source (see .github/workflows/build.yml), so this
|
||||
# must never leak into a commit.
|
||||
.cargo/config.toml
|
||||
|
||||
Generated
+412
-147
File diff suppressed because it is too large
Load Diff
@@ -24,6 +24,11 @@ vello = { git = "https://github.com/linebender/vello", branch = "main" }
|
||||
wgpu = { version = "27", features = ["vulkan", "metal", "gles"] }
|
||||
kurbo = { version = "0.12", features = ["serde"] }
|
||||
peniko = "0.5"
|
||||
# Text layout/shaping for text layers. Pinned to git main to match the peniko 0.5
|
||||
# / skrifa 0.37 that vello's git-main resolves to — a released parley still pins
|
||||
# peniko 0.4, which would split `peniko::Font` into two incompatible types at the
|
||||
# vello `draw_glyphs` boundary.
|
||||
parley = { git = "https://github.com/linebender/parley", branch = "main" }
|
||||
|
||||
# Windowing
|
||||
winit = "0.30"
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# GPU-resident video decode + dynamic decode resolution
|
||||
|
||||
## Context
|
||||
|
||||
Profiling the zero-copy H.264 export (single Group[Video, Audio] clip, `LB_RENDER_PROFILE=1`)
|
||||
broke the per-frame CPU "render" bucket down as:
|
||||
|
||||
| Cost (ms/frame) | 1080p | 4K | What it is |
|
||||
|-------------------------|-------|-------|-----------------------------------------------------|
|
||||
| decode | 3.1 | 19.0 | software ffmpeg decode (`video.rs::get_frame`) |
|
||||
| background re-render | 3.6 | 7.5 | static background pushed through Vello *every frame* |
|
||||
| video upload + blit | 4.1 | 4.2 | per-frame transient texture alloc + `write_texture` |
|
||||
| srgb | 0.4 | 0.4 | linear→sRGB pass |
|
||||
|
||||
The video correctly takes the GPU Video-instance path (not Vello-baked) — `LB_LAYER_DEBUG=1`
|
||||
shows `Video (1 instance)`. So the cost is **the video frame itself**: software decode, then an
|
||||
8 MB `write_texture` upload of the decoded RGBA every frame. At 4K, software decode (19 ms)
|
||||
dominates everything.
|
||||
|
||||
### Two correctness problems found alongside the perf issue
|
||||
|
||||
1. **Decode resolution is frozen to document size at import.** `load_video(clip, src, doc_w, doc_h)`
|
||||
(`main.rs:4302`) sizes the decoder's swscale output to the document, capped to never upscale
|
||||
(`video.rs:149`). Export *reuses that decoder*, so exporting **above** document resolution yields
|
||||
video that was decoded to ≤document res and then GPU-**up**scaled — real source detail thrown away.
|
||||
2. **It can't follow the consumer or a document resize.** Preview wants small/fast frames; export
|
||||
wants full res; changing the document size should re-target the decode. None of that works with a
|
||||
size frozen at import.
|
||||
|
||||
## Goal
|
||||
|
||||
Decouple **decode resolution** from import/document size: the renderer requests a frame *at a target
|
||||
resolution*, and the decode path produces it. Hardware-decode H.264 (and later HEVC/AV1) into a GPU
|
||||
surface and keep it GPU-resident through composite into the encoder — no CPU frame copy in either
|
||||
direction. Software decode stays a **first-class** path (codecs/platforms without HW support), decoding
|
||||
at the requested target res. This fixes the 4K decode wall, the 8 MB upload, *and* the resolution bugs.
|
||||
|
||||
## Design principles
|
||||
|
||||
- **Decode native, scale to the consumer's target.**
|
||||
- *Hardware path:* decode into a native VAAPI surface → import as a wgpu texture (reuse the
|
||||
`gpu-video-encoder` `dmabuf.rs` / `vk_device.rs` plumbing, read direction) → the GPU blit that
|
||||
already composites the Video instance scales native→target for free. Handles any target res and
|
||||
document resizes inherently; the cached frame is a native GPU texture.
|
||||
- *Software path:* decode native → `swscale` to the requested target (the reusable scaler is keyed
|
||||
on input format/size **and** output size — rebuilt when the target changes). Preview requests
|
||||
preview res (cheap); export requests export res (full quality).
|
||||
- **`VideoManager::get_frame` takes a target `(w, h)`** instead of relying on a frozen output size.
|
||||
The frame cache is keyed to handle multiple live targets (preview + export) — either cache native
|
||||
frames and scale on demand, or key by `(clip, ts, target)`; decide in Stage 2 by measuring cache
|
||||
hit/scale tradeoff.
|
||||
- **Software is not optional.** Hardware decode is an acceleration of the same `get_frame` contract,
|
||||
selected per source when the codec/driver supports it; everything falls back to software cleanly.
|
||||
|
||||
## Approach (staged; each stage compiles + is independently useful)
|
||||
|
||||
### Stage 0 — independent quick wins (not blocked on decode)
|
||||
- **Cache the static background** (`composite_document_to_hdr`): render once, reuse via a persistent
|
||||
HDR texture (copy-in each frame) instead of a full Vello render + 2 passes/submits every frame.
|
||||
Recovers ~3.6 ms (1080p) / ~7.5 ms (4K) per frame on *every* export. (In flight.)
|
||||
|
||||
### Stage 1 — software: decode at the requested target res (testable; fixes the quality bug now)
|
||||
- Change `VideoManager::get_frame(clip, ts)` → `get_frame(clip, ts, target_w, target_h)`; thread the
|
||||
target from the renderer (preview = current doc/preview res, export = export res). Cap at native.
|
||||
- Rework `VideoDecoder` so output size is per-request, not frozen at construction; cache the swscale
|
||||
context per output size (already cached per stream — extend the key). Adjust the frame cache key.
|
||||
- Result: software exports are full-quality at any export res, and document resizes re-target decode.
|
||||
No hardware needed; this is the correctness fix for the codecs HW can't handle anyway.
|
||||
|
||||
### Stage 2 — hardware decode primitive (headless-testable here, like the 8 encode tests)
|
||||
- In `gpu-video-encoder` (rename → `gpu-video-codec`): `h264_vaapi`-style **decode** → VAAPI surface →
|
||||
export DMA-BUF → import as a wgpu texture. Hardware test: decode a known file, verify dims/contents.
|
||||
|
||||
### Stage 3 — wire hardware decode into `get_frame` (blind; user-verifies)
|
||||
- When the source codec/driver is HW-decodable, `get_frame` returns a **GPU texture** (native res)
|
||||
instead of `Arc<Vec<u8>>`; the compositor uses it directly (no `write_texture`), GPU-scaling to the
|
||||
target. For the zero-copy export the frame never leaves the GPU: **decode → composite → encode** on
|
||||
one device. Software path is the fallback for everything else.
|
||||
|
||||
## Critical files
|
||||
- `lightningbeam-core/src/video.rs` — `VideoDecoder` (per-request output size, scaler cache),
|
||||
`VideoManager::get_frame` (target param, cache key).
|
||||
- `lightningbeam-core/src/renderer.rs` — pass the render target res into the video-instance build.
|
||||
- `lightningbeam-editor/src/export/video_exporter.rs` — background cache (Stage 0); consume a GPU
|
||||
texture instead of uploading RGBA (Stage 3).
|
||||
- `gpu-video-encoder/` (→ `gpu-video-codec`) — `dmabuf.rs`/`vk_device.rs` reused for the decode import.
|
||||
|
||||
## Risks
|
||||
- **Codec coverage** — only some codecs are HW-decodable per GPU/driver; software must stay correct
|
||||
and well-tested. Selection must probe support per source, not assume.
|
||||
- **Cache memory** — native-res GPU textures (esp. 4K) are large; the frame cache budget needs revisiting.
|
||||
- **Colorspace/format** — VAAPI decode surfaces are NV12/tiled; the existing import handles NV12, but
|
||||
10-bit/HDR sources (P010) need format handling.
|
||||
- **Preview vs export sharing** — two live targets (preview res + export res) from the same source; the
|
||||
cache/scaler design must serve both without thrashing.
|
||||
|
||||
## Verification
|
||||
- Stage 0/1: visual — export above document res is now full-quality (not upscaled); profile shows
|
||||
background ≈ 0 and (Stage 1) software export correct at the chosen res.
|
||||
- Stage 2: headless hardware test in `gpu-video-codec` (decode → wgpu texture, ffprobe/byte checks).
|
||||
- Stage 3 (user): 1080p + 4K H.264 export — decode/upload buckets collapse; software fallback for a
|
||||
non-HW codec (e.g. ProRes) still produces correct full-res output.
|
||||
@@ -0,0 +1,217 @@
|
||||
//! VAAPI hardware video decode → wgpu textures. The mirror of [`crate::encoder`]: the codec
|
||||
//! decodes into a VAAPI NV12 surface, which is mapped to a DRM-PRIME DMA-BUF and imported as two
|
||||
//! wgpu plane textures via [`crate::dmabuf::import_raw`] — the exact same path the encoder uses,
|
||||
//! in the read direction. Stays GPU-resident: no CPU frame copy.
|
||||
|
||||
use crate::dmabuf::{self, ImportedNv12, Nv12DmaBuf};
|
||||
use crate::vk_device::{self, DrmDevice};
|
||||
use ffmpeg_sys_next as ff;
|
||||
use std::ffi::CString;
|
||||
use std::path::Path;
|
||||
use std::ptr;
|
||||
|
||||
#[inline]
|
||||
fn averror(e: i32) -> i32 {
|
||||
-e
|
||||
}
|
||||
|
||||
/// `get_format` callback: pick VAAPI surfaces so the decoder outputs hardware frames. With
|
||||
/// `hw_device_ctx` set, FFmpeg auto-allocates the matching frames context.
|
||||
unsafe extern "C" fn get_vaapi_format(
|
||||
_ctx: *mut ff::AVCodecContext,
|
||||
mut fmts: *const ff::AVPixelFormat,
|
||||
) -> ff::AVPixelFormat {
|
||||
while *fmts != ff::AVPixelFormat::AV_PIX_FMT_NONE {
|
||||
if *fmts == ff::AVPixelFormat::AV_PIX_FMT_VAAPI {
|
||||
return ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
}
|
||||
fmts = fmts.add(1);
|
||||
}
|
||||
ff::AVPixelFormat::AV_PIX_FMT_NONE
|
||||
}
|
||||
|
||||
/// Hardware decoder for a single video file/stream. Frames come back as importable NV12 textures
|
||||
/// on [`Self::device`].
|
||||
pub struct VaapiDecoder {
|
||||
drm: DrmDevice,
|
||||
hw_device: *mut ff::AVBufferRef,
|
||||
fmt: *mut ff::AVFormatContext,
|
||||
dec: *mut ff::AVCodecContext,
|
||||
pkt: *mut ff::AVPacket,
|
||||
frame: *mut ff::AVFrame,
|
||||
stream_index: i32,
|
||||
flushing: bool,
|
||||
}
|
||||
|
||||
// Owns its FFmpeg/Vulkan handles exclusively; only moved, never shared (same as the encoder).
|
||||
unsafe impl Send for VaapiDecoder {}
|
||||
|
||||
impl VaapiDecoder {
|
||||
/// Open `input_path` and set up VAAPI hardware decoding of its best video stream.
|
||||
pub fn new(input_path: &Path) -> Result<Self, String> {
|
||||
let drm = vk_device::create()?;
|
||||
unsafe {
|
||||
let mut hw_device = crate::vaapi::create_device()?;
|
||||
let cleanup_hw = |hw: *mut ff::AVBufferRef| {
|
||||
let mut h = hw;
|
||||
ff::av_buffer_unref(&mut h);
|
||||
};
|
||||
|
||||
let path_c = CString::new(input_path.to_string_lossy().as_ref()).unwrap();
|
||||
let mut fmt: *mut ff::AVFormatContext = ptr::null_mut();
|
||||
if ff::avformat_open_input(&mut fmt, path_c.as_ptr(), ptr::null_mut(), ptr::null_mut()) < 0 {
|
||||
cleanup_hw(hw_device);
|
||||
return Err(format!("avformat_open_input {input_path:?} failed"));
|
||||
}
|
||||
if ff::avformat_find_stream_info(fmt, ptr::null_mut()) < 0 {
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("avformat_find_stream_info failed".into());
|
||||
}
|
||||
|
||||
let mut decoder: *const ff::AVCodec = ptr::null();
|
||||
let stream_index = ff::av_find_best_stream(
|
||||
fmt,
|
||||
ff::AVMediaType::AVMEDIA_TYPE_VIDEO,
|
||||
-1,
|
||||
-1,
|
||||
&mut decoder,
|
||||
0,
|
||||
);
|
||||
if stream_index < 0 || decoder.is_null() {
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("no decodable video stream".into());
|
||||
}
|
||||
|
||||
let dec = ff::avcodec_alloc_context3(decoder);
|
||||
let stream = *(*fmt).streams.add(stream_index as usize);
|
||||
if ff::avcodec_parameters_to_context(dec, (*stream).codecpar) < 0 {
|
||||
ff::avcodec_free_context(&mut (dec as *mut _));
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("avcodec_parameters_to_context failed".into());
|
||||
}
|
||||
(*dec).hw_device_ctx = ff::av_buffer_ref(hw_device);
|
||||
(*dec).get_format = Some(get_vaapi_format);
|
||||
|
||||
if ff::avcodec_open2(dec, decoder, ptr::null_mut()) < 0 {
|
||||
ff::avcodec_free_context(&mut (dec as *mut _));
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("avcodec_open2 (vaapi decode) failed".into());
|
||||
}
|
||||
|
||||
// `mut` only to satisfy the move into the struct; the binding above is consumed.
|
||||
let _ = &mut hw_device;
|
||||
Ok(Self {
|
||||
drm,
|
||||
hw_device,
|
||||
fmt,
|
||||
dec,
|
||||
pkt: ff::av_packet_alloc(),
|
||||
frame: ff::av_frame_alloc(),
|
||||
stream_index,
|
||||
flushing: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The wgpu device the decoded textures live on (the DMA-BUF-import device).
|
||||
pub fn device(&self) -> &wgpu::Device {
|
||||
&self.drm.device
|
||||
}
|
||||
pub fn queue(&self) -> &wgpu::Queue {
|
||||
&self.drm.queue
|
||||
}
|
||||
|
||||
/// Decode the next frame and import it as NV12 plane textures, or `Ok(None)` at end of stream.
|
||||
pub fn next_frame(&mut self) -> Result<Option<ImportedNv12>, String> {
|
||||
unsafe {
|
||||
loop {
|
||||
let r = ff::avcodec_receive_frame(self.dec, self.frame);
|
||||
if r == 0 {
|
||||
let imported = self.map_current();
|
||||
ff::av_frame_unref(self.frame);
|
||||
return imported.map(Some);
|
||||
}
|
||||
if r == ff::AVERROR_EOF {
|
||||
return Ok(None);
|
||||
}
|
||||
if r != averror(libc::EAGAIN) {
|
||||
return Err(format!("avcodec_receive_frame failed: {r}"));
|
||||
}
|
||||
if self.flushing {
|
||||
return Ok(None); // already drained the flush
|
||||
}
|
||||
|
||||
// Decoder wants more input: pump one packet (or signal EOF to flush).
|
||||
let rp = ff::av_read_frame(self.fmt, self.pkt);
|
||||
if rp < 0 {
|
||||
self.flushing = true;
|
||||
ff::avcodec_send_packet(self.dec, ptr::null());
|
||||
continue;
|
||||
}
|
||||
if (*self.pkt).stream_index == self.stream_index {
|
||||
let rs = ff::avcodec_send_packet(self.dec, self.pkt);
|
||||
ff::av_packet_unref(self.pkt);
|
||||
if rs < 0 && rs != averror(libc::EAGAIN) {
|
||||
return Err(format!("avcodec_send_packet failed: {rs}"));
|
||||
}
|
||||
} else {
|
||||
ff::av_packet_unref(self.pkt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Map the just-decoded VAAPI surface (`self.frame`) to a DRM-PRIME DMA-BUF and import it.
|
||||
unsafe fn map_current(&self) -> Result<ImportedNv12, String> {
|
||||
let drm_f = ff::av_frame_alloc();
|
||||
(*drm_f).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
|
||||
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32 | ff::AV_HWFRAME_MAP_READ as i32;
|
||||
if ff::av_hwframe_map(drm_f, self.frame, flags) < 0 {
|
||||
ff::av_frame_free(&mut (drm_f as *mut _));
|
||||
return Err("av_hwframe_map failed".into());
|
||||
}
|
||||
let desc = (*drm_f).data[0] as *const ff::AVDRMFrameDescriptor;
|
||||
let obj = &(*desc).objects[0];
|
||||
let width = (*self.frame).width as u32;
|
||||
let height = (*self.frame).height as u32;
|
||||
// NV12: Y then UV — either as two layers (one plane each) or one layer with two planes.
|
||||
let (y_pl, uv_pl) = if (*desc).nb_layers >= 2 {
|
||||
(&(*desc).layers[0].planes[0], &(*desc).layers[1].planes[0])
|
||||
} else {
|
||||
(&(*desc).layers[0].planes[0], &(*desc).layers[0].planes[1])
|
||||
};
|
||||
let buf = Nv12DmaBuf {
|
||||
fd: obj.fd,
|
||||
size: obj.size as u64,
|
||||
modifier: obj.format_modifier,
|
||||
width,
|
||||
height,
|
||||
y_offset: y_pl.offset as u64,
|
||||
y_pitch: y_pl.pitch as u64,
|
||||
uv_offset: uv_pl.offset as u64,
|
||||
uv_pitch: uv_pl.pitch as u64,
|
||||
ten_bit: false,
|
||||
};
|
||||
let imported = dmabuf::import_raw(&self.drm.device, &self.drm.adapter, &buf);
|
||||
ff::av_frame_free(&mut (drm_f as *mut _)); // the fd was dup'd into Vulkan
|
||||
imported
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for VaapiDecoder {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ff::av_frame_free(&mut (self.frame as *mut _));
|
||||
ff::av_packet_free(&mut (self.pkt as *mut _));
|
||||
ff::avcodec_free_context(&mut (self.dec as *mut _));
|
||||
if !self.fmt.is_null() {
|
||||
ff::avformat_close_input(&mut self.fmt);
|
||||
}
|
||||
ff::av_buffer_unref(&mut self.hw_device);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use crate::vaapi::MappedSurface;
|
||||
use crate::vk_device::DrmDevice;
|
||||
use ash::vk;
|
||||
|
||||
/// Plane layout for a single-object NV12 DMA-BUF (the common VAAPI case).
|
||||
/// Plane layout for a single-object NV12/P010 DMA-BUF (the common VAAPI case).
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Nv12DmaBuf {
|
||||
pub fd: i32,
|
||||
@@ -18,6 +18,9 @@ pub struct Nv12DmaBuf {
|
||||
pub y_pitch: u64,
|
||||
pub uv_offset: u64,
|
||||
pub uv_pitch: u64,
|
||||
/// True for 10/12/16-bit content (P010 etc.): planes are 16-bit (R16/Rg16) rather than 8-bit
|
||||
/// (R8/Rg8). The sampled float is normalized either way, so the consumer needs no change.
|
||||
pub ten_bit: bool,
|
||||
}
|
||||
|
||||
/// Frees the shared imported `VkDeviceMemory` once both plane images are gone. Held by
|
||||
@@ -33,6 +36,47 @@ impl Drop for MemoryGuard {
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees the duplicated dma-buf fd and any partially-created Vulkan objects when an import
|
||||
/// errors out before ownership has been handed to wgpu/`MemoryGuard`. `commit()` disarms it on
|
||||
/// the success path; `fd_consumed()` is called once `vkAllocateMemory` has taken the fd.
|
||||
struct ImportGuard {
|
||||
device: ash::Device,
|
||||
fd: libc::c_int,
|
||||
img_y: vk::Image,
|
||||
img_uv: vk::Image,
|
||||
memory: vk::DeviceMemory,
|
||||
armed: bool,
|
||||
}
|
||||
impl ImportGuard {
|
||||
fn fd_consumed(&mut self) {
|
||||
self.fd = -1; // vkAllocateMemory owns the fd now; don't close it ourselves
|
||||
}
|
||||
fn commit(&mut self) {
|
||||
self.armed = false;
|
||||
}
|
||||
}
|
||||
impl Drop for ImportGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.armed {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
if self.img_uv != vk::Image::null() {
|
||||
self.device.destroy_image(self.img_uv, None);
|
||||
}
|
||||
if self.img_y != vk::Image::null() {
|
||||
self.device.destroy_image(self.img_y, None);
|
||||
}
|
||||
if self.memory != vk::DeviceMemory::null() {
|
||||
self.device.free_memory(self.memory, None);
|
||||
}
|
||||
if self.fd >= 0 {
|
||||
libc::close(self.fd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A VAAPI surface imported as two wgpu plane textures. The underlying Vulkan image/
|
||||
/// memory are destroyed by wgpu (via drop callbacks) when these textures drop.
|
||||
pub struct ImportedNv12 {
|
||||
@@ -47,12 +91,17 @@ impl ImportedNv12 {
|
||||
pub fn uv(&self) -> &wgpu::Texture {
|
||||
&self.uv
|
||||
}
|
||||
/// Consume into the `(Y, UV)` plane textures (for handing to a longer-lived owner).
|
||||
pub fn into_planes(self) -> (wgpu::Texture, wgpu::Texture) {
|
||||
(self.y, self.uv)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience: map a freshly-allocated `MappedSurface` and import it.
|
||||
/// Convenience: map a freshly-allocated `MappedSurface` and import it onto `drm`.
|
||||
pub fn import(drm: &DrmDevice, surf: &MappedSurface) -> Result<ImportedNv12, String> {
|
||||
import_raw(
|
||||
drm,
|
||||
&drm.device,
|
||||
&drm.adapter,
|
||||
&Nv12DmaBuf {
|
||||
fd: surf.fd,
|
||||
size: surf.size,
|
||||
@@ -63,22 +112,61 @@ pub fn import(drm: &DrmDevice, surf: &MappedSurface) -> Result<ImportedNv12, Str
|
||||
y_pitch: surf.y_pitch,
|
||||
uv_offset: surf.uv_offset,
|
||||
uv_pitch: surf.uv_pitch,
|
||||
ten_bit: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Import an NV12 DMA-BUF (described by `buf`) as two wgpu plane textures. The fd is
|
||||
/// duplicated, so the caller keeps ownership of theirs.
|
||||
pub fn import_raw(drm: &DrmDevice, buf: &Nv12DmaBuf) -> Result<ImportedNv12, String> {
|
||||
/// Import an NV12 DMA-BUF (described by `buf`) as two wgpu plane textures **on `device`**. The raw
|
||||
/// Vulkan handles are extracted from `device`/`adapter` via `as_hal`, so this works with any
|
||||
/// DMA-BUF-import-capable wgpu device — the encoder/decoder's own `DrmDevice` *or* the editor's
|
||||
/// shared device. The fd is duplicated, so the caller keeps ownership of theirs.
|
||||
pub fn import_raw(
|
||||
device: &wgpu::Device,
|
||||
adapter: &wgpu::Adapter,
|
||||
buf: &Nv12DmaBuf,
|
||||
) -> Result<ImportedNv12, String> {
|
||||
use wgpu_hal::vulkan::Api as Vk;
|
||||
unsafe {
|
||||
let device = drm.raw_device.clone();
|
||||
let instance = &drm.raw_instance;
|
||||
let hal_device = device
|
||||
.as_hal::<Vk>()
|
||||
.ok_or("device is not Vulkan")?;
|
||||
let raw_device = hal_device.raw_device().clone();
|
||||
let raw_instance = adapter
|
||||
.as_hal::<Vk>()
|
||||
.ok_or("adapter is not Vulkan")?
|
||||
.shared_instance()
|
||||
.raw_instance()
|
||||
.clone();
|
||||
let instance = &raw_instance;
|
||||
|
||||
let dup_fd = libc::dup(buf.fd);
|
||||
if dup_fd < 0 {
|
||||
return Err("dup(dma-buf fd) failed".into());
|
||||
}
|
||||
// Owns the fd + any Vk objects created below until ownership transfers to wgpu; on any
|
||||
// early `?`/return before that, its Drop frees them (was leaking on every failed import).
|
||||
let mut guard = ImportGuard {
|
||||
device: raw_device.clone(),
|
||||
fd: dup_fd,
|
||||
img_y: vk::Image::null(),
|
||||
img_uv: vk::Image::null(),
|
||||
memory: vk::DeviceMemory::null(),
|
||||
armed: true,
|
||||
};
|
||||
|
||||
// 16-bit-norm plane formats (P010) are NOT renderable, so the import is sample-only for
|
||||
// those (decode path). 8-bit planes keep COLOR_ATTACHMENT for the encoder's RGBA→NV12 write.
|
||||
let vk_usage = if buf.ten_bit {
|
||||
vk::ImageUsageFlags::SAMPLED
|
||||
| vk::ImageUsageFlags::TRANSFER_SRC
|
||||
| vk::ImageUsageFlags::TRANSFER_DST
|
||||
} else {
|
||||
vk::ImageUsageFlags::COLOR_ATTACHMENT
|
||||
| vk::ImageUsageFlags::SAMPLED
|
||||
| vk::ImageUsageFlags::TRANSFER_SRC
|
||||
| vk::ImageUsageFlags::TRANSFER_DST
|
||||
};
|
||||
let make_image = |format: vk::Format, w: u32, h: u32, pitch: u64| -> Result<vk::Image, String> {
|
||||
let mut ext = vk::ExternalMemoryImageCreateInfo::default()
|
||||
.handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT);
|
||||
@@ -94,30 +182,41 @@ pub fn import_raw(drm: &DrmDevice, buf: &Nv12DmaBuf) -> Result<ImportedNv12, Str
|
||||
.array_layers(1)
|
||||
.samples(vk::SampleCountFlags::TYPE_1)
|
||||
.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
|
||||
.usage(
|
||||
vk::ImageUsageFlags::COLOR_ATTACHMENT
|
||||
| vk::ImageUsageFlags::TRANSFER_SRC
|
||||
| vk::ImageUsageFlags::TRANSFER_DST,
|
||||
)
|
||||
.usage(vk_usage)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE)
|
||||
.initial_layout(vk::ImageLayout::UNDEFINED)
|
||||
.push_next(&mut ext)
|
||||
.push_next(&mut drm_info);
|
||||
device
|
||||
raw_device
|
||||
.create_image(&info, None)
|
||||
.map_err(|e| format!("vkCreateImage(modifier) failed: {e:?}"))
|
||||
};
|
||||
|
||||
let img_y = make_image(vk::Format::R8_UNORM, buf.width, buf.height, buf.y_pitch)?;
|
||||
let img_uv = make_image(vk::Format::R8G8_UNORM, buf.width / 2, buf.height / 2, buf.uv_pitch)?;
|
||||
// 8-bit NV12 → R8/Rg8 planes; 10/12/16-bit P010-style → R16/Rg16 (sampled value is
|
||||
// normalized either way, so the NV12→RGB consumer is unchanged).
|
||||
let (vk_y, vk_uv) = if buf.ten_bit {
|
||||
(vk::Format::R16_UNORM, vk::Format::R16G16_UNORM)
|
||||
} else {
|
||||
(vk::Format::R8_UNORM, vk::Format::R8G8_UNORM)
|
||||
};
|
||||
let (wgpu_y, wgpu_uv) = if buf.ten_bit {
|
||||
(wgpu::TextureFormat::R16Unorm, wgpu::TextureFormat::Rg16Unorm)
|
||||
} else {
|
||||
(wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::Rg8Unorm)
|
||||
};
|
||||
|
||||
let fd_dev = ash::khr::external_memory_fd::Device::new(instance, &device);
|
||||
let img_y = make_image(vk_y, buf.width, buf.height, buf.y_pitch)?;
|
||||
guard.img_y = img_y;
|
||||
let img_uv = make_image(vk_uv, buf.width / 2, buf.height / 2, buf.uv_pitch)?;
|
||||
guard.img_uv = img_uv;
|
||||
|
||||
let fd_dev = ash::khr::external_memory_fd::Device::new(instance, &raw_device);
|
||||
let mut fd_props = vk::MemoryFdPropertiesKHR::default();
|
||||
fd_dev
|
||||
.get_memory_fd_properties(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT, dup_fd, &mut fd_props)
|
||||
.map_err(|e| format!("vkGetMemoryFdPropertiesKHR failed: {e:?}"))?;
|
||||
let req_y = device.get_image_memory_requirements(img_y);
|
||||
let req_uv = device.get_image_memory_requirements(img_uv);
|
||||
let req_y = raw_device.get_image_memory_requirements(img_y);
|
||||
let req_uv = raw_device.get_image_memory_requirements(img_uv);
|
||||
let type_bits = fd_props.memory_type_bits & req_y.memory_type_bits & req_uv.memory_type_bits;
|
||||
if type_bits == 0 {
|
||||
return Err("no memory type compatible with dma-buf + both plane images".into());
|
||||
@@ -131,28 +230,42 @@ pub fn import_raw(drm: &DrmDevice, buf: &Nv12DmaBuf) -> Result<ImportedNv12, Str
|
||||
.allocation_size(buf.size)
|
||||
.memory_type_index(mem_type)
|
||||
.push_next(&mut import_info);
|
||||
let memory = device
|
||||
let memory = raw_device
|
||||
.allocate_memory(&alloc, None)
|
||||
.map_err(|e| format!("vkAllocateMemory(import dma-buf) failed: {e:?}"))?;
|
||||
guard.fd_consumed(); // the import transferred fd ownership to Vulkan
|
||||
guard.memory = memory;
|
||||
|
||||
device
|
||||
raw_device
|
||||
.bind_image_memory(img_y, memory, buf.y_offset)
|
||||
.map_err(|e| format!("bind Y plane: {e:?}"))?;
|
||||
device
|
||||
raw_device
|
||||
.bind_image_memory(img_uv, memory, buf.uv_offset)
|
||||
.map_err(|e| format!("bind UV plane: {e:?}"))?;
|
||||
|
||||
// Shared guard: frees `memory` once both images' drop callbacks have run.
|
||||
let mem_guard = std::sync::Arc::new(MemoryGuard { device: device.clone(), memory });
|
||||
let mem_guard = std::sync::Arc::new(MemoryGuard { device: raw_device.clone(), memory });
|
||||
|
||||
let hal_device = drm
|
||||
.device
|
||||
.as_hal::<wgpu_hal::vulkan::Api>()
|
||||
.ok_or("device is not Vulkan")?;
|
||||
// Match the Vulkan usage: 16-bit-norm planes (P010) are sample-only (not renderable).
|
||||
let (hal_usage, wgpu_usage) = if buf.ten_bit {
|
||||
(
|
||||
wgpu_types::TextureUses::RESOURCE | wgpu_types::TextureUses::COPY_SRC,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
wgpu_types::TextureUses::COLOR_TARGET
|
||||
| wgpu_types::TextureUses::RESOURCE
|
||||
| wgpu_types::TextureUses::COPY_SRC,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_SRC,
|
||||
)
|
||||
};
|
||||
let wrap = |img: vk::Image, format: wgpu::TextureFormat, w: u32, h: u32| -> wgpu::Texture {
|
||||
// wgpu destroys the image (after wait-idle) when the texture drops; the
|
||||
// captured Arc<MemoryGuard> frees the shared memory once both have run.
|
||||
let dev = device.clone();
|
||||
let dev = raw_device.clone();
|
||||
let guard = mem_guard.clone();
|
||||
let cb: wgpu_hal::DropCallback = Box::new(move || {
|
||||
dev.destroy_image(img, None);
|
||||
@@ -165,12 +278,12 @@ pub fn import_raw(drm: &DrmDevice, buf: &Nv12DmaBuf) -> Result<ImportedNv12, Str
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu_types::TextureUses::COLOR_TARGET | wgpu_types::TextureUses::COPY_SRC,
|
||||
usage: hal_usage,
|
||||
memory_flags: wgpu_hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
};
|
||||
let hal_tex = hal_device.texture_from_raw(img, &hal_desc, Some(cb));
|
||||
drm.device.create_texture_from_hal::<wgpu_hal::vulkan::Api>(
|
||||
device.create_texture_from_hal::<wgpu_hal::vulkan::Api>(
|
||||
hal_tex,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("vaapi-plane"),
|
||||
@@ -179,13 +292,16 @@ pub fn import_raw(drm: &DrmDevice, buf: &Nv12DmaBuf) -> Result<ImportedNv12, Str
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
usage: wgpu_usage,
|
||||
view_formats: &[],
|
||||
},
|
||||
)
|
||||
};
|
||||
let y = wrap(img_y, wgpu::TextureFormat::R8Unorm, buf.width, buf.height);
|
||||
let uv = wrap(img_uv, wgpu::TextureFormat::Rg8Unorm, buf.width / 2, buf.height / 2);
|
||||
// Ownership of the images (→ texture drop callbacks) and memory (→ MemoryGuard) has now
|
||||
// transferred to wgpu; disarm the cleanup guard so it doesn't double-free them.
|
||||
guard.commit();
|
||||
let y = wrap(img_y, wgpu_y, buf.width, buf.height);
|
||||
let uv = wrap(img_uv, wgpu_uv, buf.width / 2, buf.height / 2);
|
||||
drop(hal_device);
|
||||
|
||||
Ok(ImportedNv12 { y, uv })
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
use crate::dmabuf::{self, ImportedNv12, Nv12DmaBuf};
|
||||
use crate::render_nv12::Rgba2Nv12;
|
||||
use crate::vk_device::{self, DrmDevice};
|
||||
use crate::vk_device;
|
||||
use ffmpeg_sys_next as ff;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::CString;
|
||||
@@ -19,7 +19,11 @@ fn averror(e: i32) -> i32 {
|
||||
}
|
||||
|
||||
pub struct ZeroCopyEncoder {
|
||||
drm: DrmDevice,
|
||||
/// wgpu handles the NV12 render runs on — either an own `DrmDevice`'s (via `new`) or the
|
||||
/// editor's shared device (via `new_on_device`). Cloned (Arc-backed) so the source can drop.
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
adapter: wgpu::Adapter,
|
||||
renderer: Rgba2Nv12,
|
||||
hw_device: *mut ff::AVBufferRef,
|
||||
frames_ref: *mut ff::AVBufferRef,
|
||||
@@ -42,15 +46,39 @@ unsafe impl Send for ZeroCopyEncoder {}
|
||||
impl ZeroCopyEncoder {
|
||||
/// Build a zero-copy `h264_vaapi` encoder writing to `output_path` (container inferred
|
||||
/// from the extension, e.g. `.mp4`). `Err` if VAAPI/the device is unavailable.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
width: u32,
|
||||
height: u32,
|
||||
framerate: i32,
|
||||
bitrate_kbps: u32,
|
||||
output_path: &Path,
|
||||
full_range: bool,
|
||||
) -> Result<Self, String> {
|
||||
// Build a dedicated DMA-BUF-import device and run the encoder on it.
|
||||
let drm = vk_device::create()?;
|
||||
let renderer = Rgba2Nv12::new(&drm.device);
|
||||
Self::new_on_device(
|
||||
drm.device, drm.queue, drm.adapter,
|
||||
width, height, framerate, bitrate_kbps, output_path, full_range,
|
||||
)
|
||||
}
|
||||
|
||||
/// Build the encoder running its NV12 render + DMA-BUF import on an existing wgpu device (the
|
||||
/// editor's shared device), so decode→composite→encode stay GPU-resident on one device. The
|
||||
/// device must have the DMA-BUF import extensions (a `DrmDevice` / `vk_device::create_windowed`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new_on_device(
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
adapter: wgpu::Adapter,
|
||||
width: u32,
|
||||
height: u32,
|
||||
framerate: i32,
|
||||
bitrate_kbps: u32,
|
||||
output_path: &Path,
|
||||
full_range: bool,
|
||||
) -> Result<Self, String> {
|
||||
let renderer = Rgba2Nv12::new(&device, full_range);
|
||||
unsafe {
|
||||
let mut hw_device = crate::vaapi::create_device()?;
|
||||
let name = CString::new("h264_vaapi").unwrap();
|
||||
@@ -66,6 +94,17 @@ impl ZeroCopyEncoder {
|
||||
(*enc).framerate = ff::AVRational { num: framerate, den: 1 };
|
||||
(*enc).pix_fmt = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
(*enc).bit_rate = (bitrate_kbps as i64) * 1000;
|
||||
// Color signalling for the H.264 VUI. The Rgba2Nv12 shader produces BT.709 luma/chroma
|
||||
// in the matching range; without these tags players assume limited range and a
|
||||
// full-range stream looks dark + oversaturated.
|
||||
(*enc).color_range = if full_range {
|
||||
ff::AVColorRange::AVCOL_RANGE_JPEG
|
||||
} else {
|
||||
ff::AVColorRange::AVCOL_RANGE_MPEG
|
||||
};
|
||||
(*enc).colorspace = ff::AVColorSpace::AVCOL_SPC_BT709;
|
||||
(*enc).color_primaries = ff::AVColorPrimaries::AVCOL_PRI_BT709;
|
||||
(*enc).color_trc = ff::AVColorTransferCharacteristic::AVCOL_TRC_BT709;
|
||||
|
||||
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
|
||||
{
|
||||
@@ -140,7 +179,9 @@ impl ZeroCopyEncoder {
|
||||
let stream_tb = (*stream).time_base;
|
||||
|
||||
Ok(Self {
|
||||
drm,
|
||||
device,
|
||||
queue,
|
||||
adapter,
|
||||
renderer,
|
||||
hw_device,
|
||||
frames_ref,
|
||||
@@ -159,10 +200,10 @@ impl ZeroCopyEncoder {
|
||||
|
||||
/// The wgpu device frames must be rendered on (so the RGBA texture is importable).
|
||||
pub fn device(&self) -> &wgpu::Device {
|
||||
&self.drm.device
|
||||
&self.device
|
||||
}
|
||||
pub fn queue(&self) -> &wgpu::Queue {
|
||||
&self.drm.queue
|
||||
&self.queue
|
||||
}
|
||||
|
||||
/// Render `rgba` (an `Rgba8Unorm` texture on [`Self::device`], `TEXTURE_BINDING`)
|
||||
@@ -201,8 +242,9 @@ impl ZeroCopyEncoder {
|
||||
y_pitch: y.pitch as u64,
|
||||
uv_offset: uv.offset as u64,
|
||||
uv_pitch: uv.pitch as u64,
|
||||
ten_bit: false,
|
||||
};
|
||||
let imported = match dmabuf::import_raw(&self.drm, &buf) {
|
||||
let imported = match dmabuf::import_raw(&self.device, &self.adapter, &buf) {
|
||||
Ok(i) => i,
|
||||
Err(e) => {
|
||||
ff::av_frame_free(&mut (drm_f as *mut _));
|
||||
@@ -219,10 +261,10 @@ impl ZeroCopyEncoder {
|
||||
let rgba_view = rgba.create_view(&Default::default());
|
||||
let y_view = imp.y().create_view(&Default::default());
|
||||
let uv_view = imp.uv().create_view(&Default::default());
|
||||
let mut cmd = self.drm.device.create_command_encoder(&Default::default());
|
||||
self.renderer.convert(&self.drm.device, &mut cmd, &rgba_view, &y_view, &uv_view);
|
||||
self.drm.queue.submit(Some(cmd.finish()));
|
||||
let _ = self.drm.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let mut cmd = self.device.create_command_encoder(&Default::default());
|
||||
self.renderer.convert(&self.device, &mut cmd, &rgba_view, &y_view, &uv_view);
|
||||
self.queue.submit(Some(cmd.finish()));
|
||||
let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
// Encode the surface.
|
||||
(*surf).pts = self.pts;
|
||||
|
||||
@@ -30,6 +30,10 @@ pub mod dmabuf;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod encoder;
|
||||
|
||||
/// VAAPI hardware decode → wgpu textures (Linux).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod decoder;
|
||||
|
||||
#[cfg(test)]
|
||||
mod probe_tests {
|
||||
/// Confirm a headless GPU adapter is reachable (Vulkan on Linux/Intel). This gates
|
||||
|
||||
@@ -2,29 +2,61 @@
|
||||
//! surface's plane textures (R8 Y, RG8 UV). Render targets (not compute storage) so it
|
||||
//! works with the DMA-BUF-imported plane images, which aren't storage-writable.
|
||||
//!
|
||||
//! BT.709 full-range, matching `nv12::cpu_reference` and the encoder's color tags.
|
||||
//! BT.709 matrix; the Y/chroma scale+offset are chosen by `full_range` — limited (TV, 16–235)
|
||||
//! is the H.264 convention most players assume, full (PC, 0–255) needs the matching color tag.
|
||||
|
||||
/// Converts a bound RGBA texture into a Y plane (R8) and a UV plane (RG8) via two passes.
|
||||
pub struct Rgba2Nv12 {
|
||||
y_pipeline: wgpu::RenderPipeline,
|
||||
uv_pipeline: wgpu::RenderPipeline,
|
||||
bgl: wgpu::BindGroupLayout,
|
||||
params_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
impl Rgba2Nv12 {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
/// `full_range`: true → full/PC range (Y 0–255, no scaling); false → limited/TV range
|
||||
/// (Y 16–235, chroma 16–240), the H.264 default. The encoder must tag the stream to match.
|
||||
pub fn new(device: &wgpu::Device, full_range: bool) -> Self {
|
||||
// (y_offset, y_scale, chroma_offset, chroma_scale). The shader applies these to the
|
||||
// BT.709 luma/chroma dot products.
|
||||
let params: [f32; 4] = if full_range {
|
||||
[0.0, 1.0, 128.0 / 255.0, 1.0]
|
||||
} else {
|
||||
[16.0 / 255.0, 219.0 / 255.0, 128.0 / 255.0, 224.0 / 255.0]
|
||||
};
|
||||
let params_bytes: Vec<u8> = params.iter().flat_map(|f| f.to_le_bytes()).collect();
|
||||
let params_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("rgba2nv12_params"),
|
||||
size: params_bytes.len() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
params_buf.slice(..).get_mapped_range_mut().copy_from_slice(¶ms_bytes);
|
||||
params_buf.unmap();
|
||||
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("rgba2nv12_bgl"),
|
||||
entries: &[wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
count: None,
|
||||
}],
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("rgba2nv12_pl"),
|
||||
@@ -65,6 +97,7 @@ impl Rgba2Nv12 {
|
||||
y_pipeline: mk("y_fs", wgpu::TextureFormat::R8Unorm),
|
||||
uv_pipeline: mk("uv_fs", wgpu::TextureFormat::Rg8Unorm),
|
||||
bgl,
|
||||
params_buf,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,10 +113,16 @@ impl Rgba2Nv12 {
|
||||
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("rgba2nv12_bg"),
|
||||
layout: &self.bgl,
|
||||
entries: &[wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(rgba_view),
|
||||
}],
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(rgba_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.params_buf.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
for (pipeline, view) in [(&self.y_pipeline, y_view), (&self.uv_pipeline, uv_view)] {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
@@ -110,6 +149,8 @@ impl Rgba2Nv12 {
|
||||
|
||||
const SHADER: &str = r#"
|
||||
@group(0) @binding(0) var input_rgba: texture_2d<f32>;
|
||||
// (y_offset, y_scale, chroma_offset, chroma_scale) — selects limited vs full range.
|
||||
@group(0) @binding(1) var<uniform> params: vec4<f32>;
|
||||
|
||||
// Fullscreen triangle.
|
||||
@vertex
|
||||
@@ -127,7 +168,8 @@ fn load(p: vec2<i32>) -> vec3<f32> {
|
||||
@fragment
|
||||
fn y_fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let c = load(vec2<i32>(i32(pos.x), i32(pos.y)));
|
||||
let y = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
let luma = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
let y = params.x + params.y * luma;
|
||||
return vec4<f32>(y, 0.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
@@ -138,8 +180,10 @@ fn uv_fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let sy = 2 * i32(pos.y);
|
||||
let a = (load(vec2<i32>(sx, sy)) + load(vec2<i32>(sx + 1, sy))
|
||||
+ load(vec2<i32>(sx, sy + 1)) + load(vec2<i32>(sx + 1, sy + 1))) * 0.25;
|
||||
let u = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b + 0.5;
|
||||
let v = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b + 0.5;
|
||||
let cb = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b;
|
||||
let cr = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b;
|
||||
let u = params.z + params.w * cb;
|
||||
let v = params.z + params.w * cr;
|
||||
return vec4<f32>(u, v, 0.0, 1.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
@@ -157,10 +157,18 @@ impl MappedSurface {
|
||||
let desc = (*drm).data[0] as *const ff::AVDRMFrameDescriptor;
|
||||
// Expect 1 object, 2 layers (Y=R8, UV=GR88).
|
||||
if (*desc).nb_objects != 1 || (*desc).nb_layers != 2 {
|
||||
return Err(format!(
|
||||
let msg = format!(
|
||||
"unexpected DRM layout: {} objects, {} layers",
|
||||
(*desc).nb_objects, (*desc).nb_layers
|
||||
));
|
||||
);
|
||||
// Free everything mapped/allocated above (this path was leaking the device,
|
||||
// frames context, and both AVFrames on every odd-layout surface).
|
||||
ff::av_frame_free(&mut (drm as *mut _));
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err(msg);
|
||||
}
|
||||
let obj = &(*desc).objects[0];
|
||||
let y = &(*desc).layers[0].planes[0];
|
||||
|
||||
@@ -22,12 +22,20 @@ pub struct DrmDevice {
|
||||
pub raw_instance: ash::Instance,
|
||||
}
|
||||
|
||||
/// Create the device, or `Err` if Vulkan/the extension isn't available (caller falls back).
|
||||
/// Create a headless DMA-BUF-import device (encoder/decoder), or `Err` if Vulkan/the extension
|
||||
/// isn't available (caller falls back).
|
||||
pub fn create() -> Result<DrmDevice, String> {
|
||||
unsafe { create_inner() }
|
||||
unsafe { create_inner(false) }
|
||||
}
|
||||
|
||||
unsafe fn create_inner() -> Result<DrmDevice, String> {
|
||||
/// Like [`create`] but also enables `VK_KHR_swapchain` so the device can present to a window —
|
||||
/// for use as the editor's **shared** wgpu device (eframe + compositor + decode + encode all on
|
||||
/// one device, so hardware-decoded DMA-BUF textures are usable by the preview compositor).
|
||||
pub fn create_windowed() -> Result<DrmDevice, String> {
|
||||
unsafe { create_inner(true) }
|
||||
}
|
||||
|
||||
unsafe fn create_inner(windowed: bool) -> Result<DrmDevice, String> {
|
||||
use wgpu_hal::vulkan::Api as Vk;
|
||||
// Bring the HAL Instance trait into scope for `init` / `enumerate_adapters`.
|
||||
use wgpu_hal::Instance as _;
|
||||
@@ -72,14 +80,19 @@ unsafe fn create_inner() -> Result<DrmDevice, String> {
|
||||
exposed.adapter.required_device_extensions(exposed.features);
|
||||
// Only the genuine extensions; external_memory / bind_memory2 / ycbcr / format_list
|
||||
// are core in Vulkan 1.1+ (this device is 1.3) so they need no enabling.
|
||||
let extra: &[&'static CStr] = &[
|
||||
let mut extra: Vec<&'static CStr> = vec![
|
||||
ash::ext::image_drm_format_modifier::NAME,
|
||||
ash::khr::external_memory_fd::NAME,
|
||||
ash::ext::external_memory_dma_buf::NAME,
|
||||
ash::ext::queue_family_foreign::NAME,
|
||||
];
|
||||
// Presentation (windowed shared device only): the WSI surface instance extensions are already
|
||||
// enabled by `Instance::init`; the device needs the swapchain extension to present.
|
||||
if windowed {
|
||||
extra.push(ash::khr::swapchain::NAME);
|
||||
}
|
||||
for e in extra {
|
||||
if !ext_names.contains(e) {
|
||||
if !ext_names.contains(&e) {
|
||||
ext_names.push(e);
|
||||
}
|
||||
}
|
||||
@@ -130,7 +143,10 @@ unsafe fn create_inner() -> Result<DrmDevice, String> {
|
||||
open_device,
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: Some("drm-import-device"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
// R16/Rg16 plane textures for P010 (10-bit HDR) import need this; request it only
|
||||
// when the adapter supports it (else 10-bit falls back to software decode).
|
||||
required_features: wgpu_adapter.features()
|
||||
& wgpu::Features::TEXTURE_FORMAT_16BIT_NORM,
|
||||
// Vello's compute pipelines need more than downlevel limits (e.g.
|
||||
// max_storage_buffers_per_shader_stage >= 5). This device only ever runs on a
|
||||
// real VAAPI-capable GPU, so request the adapter's full limits.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Round-trip: encode solid frames with the zero-copy encoder, then hardware-decode them back
|
||||
//! into a wgpu texture and read the Y plane. Verifies the VAAPI decode → DMA-BUF → wgpu import
|
||||
//! path produces real pixels on the GPU. Skips when VAAPI is unavailable.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use gpu_video_encoder::decoder::VaapiDecoder;
|
||||
use gpu_video_encoder::encoder::ZeroCopyEncoder;
|
||||
|
||||
#[test]
|
||||
fn vaapi_decode_roundtrip() {
|
||||
// 256-wide so the R8 Y readback row (256 B) is already 256-aligned.
|
||||
let (w, h) = (256u32, 256u32);
|
||||
let out = std::env::temp_dir().join("gpu_video_encoder_decode_rt.mp4");
|
||||
let _ = std::fs::remove_file(&out);
|
||||
|
||||
// --- Encode 10 frames of solid mid-gray. Full range → Y == luma ≈ 128. ---
|
||||
{
|
||||
let mut enc = match ZeroCopyEncoder::new(w, h, 30, 4000, &out, true) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
eprintln!("[decode-rt] encode unavailable, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let device = enc.device();
|
||||
let src = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("gray"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let gray = vec![128u8; (w * h * 4) as usize];
|
||||
enc.queue().write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: &src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
&gray,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
for _ in 0..10 {
|
||||
enc.encode_rgba(&src).expect("encode_rgba");
|
||||
}
|
||||
enc.finish().expect("finish");
|
||||
}
|
||||
|
||||
// --- Decode it back on the GPU. ---
|
||||
let mut dec = match VaapiDecoder::new(&out) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("[decode-rt] decode unavailable, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let frame = dec.next_frame().expect("next_frame").expect("expected at least one frame");
|
||||
assert_eq!(frame.y().width(), w, "decoded Y width");
|
||||
assert_eq!(frame.y().height(), h, "decoded Y height");
|
||||
|
||||
// Read back the Y plane (R8) and check it's ≈ the gray we encoded.
|
||||
let device = dec.device();
|
||||
let buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("y_readback"),
|
||||
size: (w * h) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut cmd = device.create_command_encoder(&Default::default());
|
||||
cmd.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: frame.y(), mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buf,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w), rows_per_image: Some(h) },
|
||||
},
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
dec.queue().submit(Some(cmd.finish()));
|
||||
buf.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
let data = buf.slice(..).get_mapped_range();
|
||||
let mean = data.iter().map(|&b| b as f64).sum::<f64>() / data.len() as f64;
|
||||
eprintln!("[decode-rt] decoded {w}x{h}, mean Y = {mean:.1}");
|
||||
assert!(
|
||||
(mean - 128.0).abs() < 12.0,
|
||||
"mean Y {mean} not ≈ 128 — decode produced wrong pixels"
|
||||
);
|
||||
eprintln!("[decode-rt] ✅ VAAPI decode → wgpu texture verified");
|
||||
}
|
||||
@@ -54,7 +54,7 @@ fn zerocopy_real_frame_render() {
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
|
||||
let conv = render_nv12::Rgba2Nv12::new(&drm.device);
|
||||
let conv = render_nv12::Rgba2Nv12::new(&drm.device, true);
|
||||
let src_view = src.create_view(&Default::default());
|
||||
let y_view = imported.y().create_view(&Default::default());
|
||||
let uv_view = imported.uv().create_view(&Default::default());
|
||||
|
||||
@@ -10,7 +10,7 @@ fn zerocopy_encode_h264() {
|
||||
let (w, h) = (640u32, 480u32);
|
||||
let out = std::env::temp_dir().join("gpu_video_encoder_zerocopy.mp4");
|
||||
let _ = std::fs::remove_file(&out);
|
||||
let mut enc = match ZeroCopyEncoder::new(w, h, 30, 4000, &out) {
|
||||
let mut enc = match ZeroCopyEncoder::new(w, h, 30, 4000, &out, false) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
eprintln!("[zc-encode] unavailable, skipping: {e}");
|
||||
|
||||
@@ -18,6 +18,9 @@ bytemuck = { version = "1.14", features = ["derive"] }
|
||||
kurbo = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
|
||||
# Text layout/shaping (text layers)
|
||||
parley = { workspace = true }
|
||||
|
||||
# Image decoding for image fills
|
||||
image = { workspace = true }
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,14 @@
|
||||
Bundled fonts for Lightningbeam text layers
|
||||
===========================================
|
||||
|
||||
These are the Liberation fonts, used as the built-in serif / sans-serif / monospaced
|
||||
families so text renders deterministically without depending on system fonts:
|
||||
|
||||
LiberationSans-Regular.ttf
|
||||
LiberationSerif-Regular.ttf
|
||||
LiberationMono-Regular.ttf
|
||||
|
||||
License: SIL Open Font License, Version 1.1.
|
||||
Copyright (c) Red Hat, Inc., with Reserved Font Name "Liberation".
|
||||
Full license text: https://openfontlicense.org/ (also distributed with the Liberation
|
||||
fonts package as its OFL.txt / LICENSE).
|
||||
@@ -104,7 +104,7 @@ impl Action for AddClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
return Err("Cannot add clip instances directly to group layers".to_string());
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
return Err("Cannot add clip instances directly to group layers".to_string());
|
||||
}
|
||||
}
|
||||
@@ -145,8 +145,8 @@ impl Action for AddClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
// Group layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances, nothing to rollback
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
// Raster/text layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
}
|
||||
self.executed = false;
|
||||
|
||||
@@ -138,6 +138,7 @@ impl Action for AddLayerAction {
|
||||
AnyLayer::Effect(_) => "Add effect layer",
|
||||
AnyLayer::Group(_) => "Add group layer",
|
||||
AnyLayer::Raster(_) => "Add raster layer",
|
||||
AnyLayer::Text(_) => "Add text layer",
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Create-text-clip action
|
||||
//!
|
||||
//! Used by the text tool when the active layer is a **vector** layer: it creates a
|
||||
//! VectorClip containing a single text layer, registers it, and places a clip
|
||||
//! instance in the parent vector layer. The editor then enters that clip so the
|
||||
//! text is directly editable. All of this is one undoable step so undo never
|
||||
//! leaves an orphan clip.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::clip::{ClipInstance, VectorClip};
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::text_layer::TextLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Minimum clip duration (seconds) when the document has no duration set yet.
|
||||
const FALLBACK_DURATION: f64 = 10.0;
|
||||
|
||||
pub struct CreateTextClipAction {
|
||||
/// The vector layer to place the clip instance in.
|
||||
parent_layer_id: Uuid,
|
||||
/// The text layer to embed (its id is stable across redo).
|
||||
text_layer: TextLayer,
|
||||
/// Instance position in the parent layer's space.
|
||||
position: (f64, f64),
|
||||
|
||||
// Assigned on first execute; reused on redo so ids are stable.
|
||||
clip_id: Option<Uuid>,
|
||||
instance_id: Option<Uuid>,
|
||||
executed: bool,
|
||||
}
|
||||
|
||||
impl CreateTextClipAction {
|
||||
pub fn new(parent_layer_id: Uuid, text_layer: TextLayer, position: (f64, f64)) -> Self {
|
||||
Self {
|
||||
parent_layer_id,
|
||||
text_layer,
|
||||
position,
|
||||
clip_id: None,
|
||||
instance_id: None,
|
||||
executed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Preset the clip + instance ids (so the caller knows them up-front for
|
||||
/// entering the clip immediately after execute). Ids stay stable across redo.
|
||||
pub fn with_ids(mut self, clip_id: Uuid, instance_id: Uuid) -> Self {
|
||||
self.clip_id = Some(clip_id);
|
||||
self.instance_id = Some(instance_id);
|
||||
self
|
||||
}
|
||||
|
||||
/// The vector clip id (after execute).
|
||||
pub fn clip_id(&self) -> Option<Uuid> {
|
||||
self.clip_id
|
||||
}
|
||||
|
||||
/// The clip instance id placed in the parent layer (after execute).
|
||||
pub fn instance_id(&self) -> Option<Uuid> {
|
||||
self.instance_id
|
||||
}
|
||||
|
||||
/// The embedded text layer's id.
|
||||
pub fn text_layer_id(&self) -> Uuid {
|
||||
self.text_layer.layer.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for CreateTextClipAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let clip_id = self.clip_id.unwrap_or_else(Uuid::new_v4);
|
||||
self.clip_id = Some(clip_id);
|
||||
let instance_id = self.instance_id.unwrap_or_else(Uuid::new_v4);
|
||||
self.instance_id = Some(instance_id);
|
||||
|
||||
let duration = if document.duration > 0.0 { document.duration } else { FALLBACK_DURATION };
|
||||
|
||||
// Build the clip with the text layer as its single root layer.
|
||||
let mut clip = VectorClip::with_id(
|
||||
clip_id,
|
||||
"Text",
|
||||
self.text_layer.box_width.max(1.0),
|
||||
self.text_layer.box_height.max(1.0),
|
||||
duration,
|
||||
);
|
||||
// A movie clip (not keyframe-gated) so the text persists across the timeline.
|
||||
clip.is_group = false;
|
||||
clip.layers.add_root(AnyLayer::Text(self.text_layer.clone()));
|
||||
// Registers the clip and its layers in layer_to_clip_map for O(1) lookup.
|
||||
document.add_vector_clip(clip);
|
||||
|
||||
// Place an instance of the clip in the parent vector layer.
|
||||
let layer = document
|
||||
.get_layer_mut(&self.parent_layer_id)
|
||||
.ok_or_else(|| format!("Parent layer {} not found", self.parent_layer_id))?;
|
||||
let AnyLayer::Vector(vector_layer) = layer else {
|
||||
return Err("Text clip can only be created inside a vector layer".to_string());
|
||||
};
|
||||
let mut instance = ClipInstance::with_id(instance_id, clip_id);
|
||||
instance.transform.x = self.position.0;
|
||||
instance.transform.y = self.position.1;
|
||||
vector_layer.clip_instances.push(instance);
|
||||
|
||||
self.executed = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if !self.executed {
|
||||
return Ok(());
|
||||
}
|
||||
// Remove the clip instance from the parent layer.
|
||||
if let (Some(instance_id), Some(AnyLayer::Vector(vector_layer))) =
|
||||
(self.instance_id, document.get_layer_mut(&self.parent_layer_id))
|
||||
{
|
||||
vector_layer.clip_instances.retain(|ci| ci.id != instance_id);
|
||||
}
|
||||
// Remove the clip and its layer_to_clip_map registrations.
|
||||
if let Some(clip_id) = self.clip_id {
|
||||
if let Some(clip) = document.vector_clips.remove(&clip_id) {
|
||||
for node in &clip.layers.roots {
|
||||
document.layer_to_clip_map.remove(&node.data.id());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.executed = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Add text".to_string()
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ impl Action for LoopClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
for (instance_id, _old_dur, new_dur, _old_lb, new_lb) in loops {
|
||||
@@ -61,6 +62,7 @@ impl Action for LoopClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
for (instance_id, old_dur, _new_dur, old_lb, _new_lb) in loops {
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod add_layer;
|
||||
pub mod add_shape;
|
||||
pub mod modify_shape_path;
|
||||
pub mod move_clip_instances;
|
||||
pub mod reorder_clip_instances;
|
||||
pub mod paint_bucket;
|
||||
pub mod remove_effect;
|
||||
pub mod set_document_properties;
|
||||
@@ -40,9 +41,13 @@ pub mod raster_diff;
|
||||
pub mod raster_stroke;
|
||||
pub mod raster_fill;
|
||||
pub mod add_raster_keyframe;
|
||||
pub mod resize_raster_layer;
|
||||
pub mod move_layer;
|
||||
pub mod set_fill_paint;
|
||||
pub mod set_image_fill;
|
||||
pub mod create_text_clip;
|
||||
pub mod set_text_content;
|
||||
pub mod resize_text_box;
|
||||
|
||||
pub use add_clip_instance::AddClipInstanceAction;
|
||||
pub use add_effect::AddEffectAction;
|
||||
@@ -50,6 +55,7 @@ pub use add_layer::AddLayerAction;
|
||||
pub use add_shape::AddShapeAction;
|
||||
pub use modify_shape_path::ModifyGraphAction;
|
||||
pub use move_clip_instances::MoveClipInstancesAction;
|
||||
pub use reorder_clip_instances::ReorderClipInstancesAction;
|
||||
pub use paint_bucket::PaintBucketAction;
|
||||
pub use remove_effect::RemoveEffectAction;
|
||||
pub use set_document_properties::SetDocumentPropertiesAction;
|
||||
@@ -77,8 +83,12 @@ pub use group_layers::GroupLayersAction;
|
||||
pub use raster_stroke::RasterStrokeAction;
|
||||
pub use raster_fill::RasterFillAction;
|
||||
pub use add_raster_keyframe::AddRasterKeyframeAction;
|
||||
pub use resize_raster_layer::ResizeRasterLayerAction;
|
||||
pub use move_layer::MoveLayerAction;
|
||||
pub use set_fill_paint::SetFillPaintAction;
|
||||
pub use set_image_fill::SetImageFillAction;
|
||||
pub use change_bpm::ChangeBpmAction;
|
||||
pub use change_fps::ChangeFpsAction;
|
||||
pub use create_text_clip::CreateTextClipAction;
|
||||
pub use set_text_content::SetTextContentAction;
|
||||
pub use resize_text_box::ResizeTextBoxAction;
|
||||
|
||||
@@ -58,6 +58,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -97,6 +98,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let group: Vec<(Uuid, f64, f64)> = moves.iter().filter_map(|(id, old_start, _)| {
|
||||
@@ -132,6 +134,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Update timeline_start for each clip instance
|
||||
@@ -159,6 +162,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Restore original timeline_start for each clip instance
|
||||
|
||||
@@ -98,11 +98,16 @@ impl RasterDiff {
|
||||
self.before_region.len() + self.after_region.len()
|
||||
}
|
||||
|
||||
/// Restore the pre-edit pixels into `raw` (undo / first-execute rollback).
|
||||
pub fn apply_before(&self, raw: &mut Vec<u8>) {
|
||||
/// Restore the pre-edit pixels into `raw` (undo / first-execute rollback). `cur_w`/`cur_h`
|
||||
/// are the keyframe's current dimensions; if they differ from the diff's captured size the
|
||||
/// diff predates a resize and is skipped rather than applied at mismatched dims.
|
||||
pub fn apply_before(&self, raw: &mut Vec<u8>, cur_w: u32, cur_h: u32) {
|
||||
if self.bbox.is_none() {
|
||||
return; // no change
|
||||
}
|
||||
if cur_w != self.full_width || cur_h != self.full_height {
|
||||
return; // diff predates a keyframe resize
|
||||
}
|
||||
if self.before_blank {
|
||||
// The frame was blank before this edit (it was the first stroke); undoing
|
||||
// it returns to blank regardless of the current buffer.
|
||||
@@ -112,11 +117,16 @@ impl RasterDiff {
|
||||
self.stamp_resident(&self.before_region, raw);
|
||||
}
|
||||
|
||||
/// Apply the post-edit pixels into `raw` (commit / redo).
|
||||
pub fn apply_after(&self, raw: &mut Vec<u8>) {
|
||||
/// Apply the post-edit pixels into `raw` (commit / redo). `cur_w`/`cur_h` are the keyframe's
|
||||
/// current dimensions; a mismatch with the captured size means the diff predates a resize, so
|
||||
/// it's skipped rather than rebuilding the buffer at stale dimensions.
|
||||
pub fn apply_after(&self, raw: &mut Vec<u8>, cur_w: u32, cur_h: u32) {
|
||||
if self.bbox.is_none() {
|
||||
return; // no change
|
||||
}
|
||||
if cur_w != self.full_width || cur_h != self.full_height {
|
||||
return; // diff predates a keyframe resize
|
||||
}
|
||||
if self.before_blank {
|
||||
// Base was blank: build a full transparent buffer then stamp the bbox. The
|
||||
// commit/redo path frequently starts from empty `raw_pixels` here.
|
||||
@@ -175,9 +185,9 @@ mod tests {
|
||||
assert_eq!(diff.bbox, Some((3, 2, 2, 2)));
|
||||
|
||||
let mut buf = after.clone();
|
||||
diff.apply_before(&mut buf);
|
||||
diff.apply_before(&mut buf, w, h);
|
||||
assert_eq!(buf, before, "undo must reproduce the pre-edit buffer exactly");
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after, "redo must reproduce the post-edit buffer exactly");
|
||||
}
|
||||
|
||||
@@ -195,15 +205,15 @@ mod tests {
|
||||
// First execute / redo from EMPTY raw_pixels (the real commit path): builds
|
||||
// the full buffer from transparent + the stroke.
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after, "commit/redo must build the frame from a blank base");
|
||||
|
||||
// Undo the first stroke → back to blank (empty).
|
||||
diff.apply_before(&mut buf);
|
||||
diff.apply_before(&mut buf, w, h);
|
||||
assert!(buf.is_empty(), "undoing the first stroke restores the blank keyframe");
|
||||
|
||||
// Redo again from the now-empty buffer.
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after);
|
||||
}
|
||||
|
||||
@@ -215,7 +225,7 @@ mod tests {
|
||||
assert_eq!(diff.bbox, None);
|
||||
assert_eq!(diff.byte_size(), 0);
|
||||
let mut b = buf.clone();
|
||||
diff.apply_before(&mut b);
|
||||
diff.apply_before(&mut b, w, h);
|
||||
assert_eq!(b, buf);
|
||||
}
|
||||
|
||||
@@ -226,7 +236,7 @@ mod tests {
|
||||
let after = solid(w, h, [1, 2, 3, 255]);
|
||||
let diff = RasterDiff::compute(&before, &after, w, h);
|
||||
let mut empty: Vec<u8> = Vec::new();
|
||||
diff.apply_before(&mut empty); // base not resident
|
||||
diff.apply_before(&mut empty, w, h); // base not resident
|
||||
assert!(empty.is_empty(), "must not resize/corrupt a non-resident base");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ impl Action for RasterFillAction {
|
||||
if let Some(full) = self.full_after.take() {
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
self.diff.apply_after(&mut kf.raw_pixels);
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
@@ -71,7 +71,7 @@ impl Action for RasterFillAction {
|
||||
let kf = raster
|
||||
.keyframe_at_mut(self.time)
|
||||
.ok_or_else(|| format!("No raster keyframe at/before t={}", self.time))?;
|
||||
self.diff.apply_before(&mut kf.raw_pixels);
|
||||
self.diff.apply_before(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
|
||||
@@ -61,7 +61,7 @@ impl Action for RasterStrokeAction {
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
// Redo: replay via the diff onto the (resident) base.
|
||||
self.diff.apply_after(&mut kf.raw_pixels);
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
@@ -70,7 +70,7 @@ impl Action for RasterStrokeAction {
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let kf = get_keyframe_mut(document, &self.layer_id, self.time, self.width, self.height)?;
|
||||
self.diff.apply_before(&mut kf.raw_pixels);
|
||||
self.diff.apply_before(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
|
||||
@@ -46,6 +46,7 @@ impl Action for RemoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Find and remove the instance, saving it for rollback
|
||||
@@ -72,6 +73,7 @@ impl Action for RemoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
clip_instances.push(instance);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Reorder clip instances within a layer's stacking order (Send to Back / Bring to Front).
|
||||
//!
|
||||
//! A layer's `clip_instances` Vec order *is* the stacking order — the last element renders on top
|
||||
//! (hit-testing walks it in reverse). Geometry renders underneath and is unaffected. This action
|
||||
//! moves the selected instances to the front (end) or back (start) of that Vec.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct ReorderClipInstancesAction {
|
||||
layer_id: Uuid,
|
||||
instance_ids: Vec<Uuid>,
|
||||
/// `true` = bring to front (top), `false` = send to back (bottom).
|
||||
to_front: bool,
|
||||
/// Full instance order captured on `execute`, for `rollback`.
|
||||
old_order: Option<Vec<Uuid>>,
|
||||
}
|
||||
|
||||
impl ReorderClipInstancesAction {
|
||||
pub fn new(layer_id: Uuid, instance_ids: Vec<Uuid>, to_front: bool) -> Self {
|
||||
Self { layer_id, instance_ids, to_front, old_order: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The clip-instance stack for a layer, if it has one (Group/Raster/Text don't).
|
||||
fn clip_instances_mut<'a>(document: &'a mut Document, layer_id: &Uuid) -> Option<&'a mut Vec<ClipInstance>> {
|
||||
match document.get_layer_mut(layer_id)? {
|
||||
AnyLayer::Vector(l) => Some(&mut l.clip_instances),
|
||||
AnyLayer::Audio(l) => Some(&mut l.clip_instances),
|
||||
AnyLayer::Video(l) => Some(&mut l.clip_instances),
|
||||
AnyLayer::Effect(l) => Some(&mut l.clip_instances),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ReorderClipInstancesAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let instances = clip_instances_mut(document, &self.layer_id)
|
||||
.ok_or_else(|| "Layer has no clip-instance stack".to_string())?;
|
||||
self.old_order = Some(instances.iter().map(|c| c.id).collect());
|
||||
|
||||
let mut selected = Vec::new();
|
||||
let mut rest = Vec::new();
|
||||
for ci in instances.drain(..) {
|
||||
if self.instance_ids.contains(&ci.id) {
|
||||
selected.push(ci);
|
||||
} else {
|
||||
rest.push(ci);
|
||||
}
|
||||
}
|
||||
if self.to_front {
|
||||
rest.extend(selected); // selected last → rendered on top
|
||||
*instances = rest;
|
||||
} else {
|
||||
selected.extend(rest); // selected first → rendered at the bottom (of the stack)
|
||||
*instances = selected;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(order) = self.old_order.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
let instances = clip_instances_mut(document, &self.layer_id)
|
||||
.ok_or_else(|| "Layer has no clip-instance stack".to_string())?;
|
||||
let rank = |id: &Uuid| order.iter().position(|o| o == id).unwrap_or(usize::MAX);
|
||||
instances.sort_by(|a, b| rank(&a.id).cmp(&rank(&b.id)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
if self.to_front { "Bring to Front".to_string() } else { "Send to Back".to_string() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Resize every keyframe of a raster layer to a new canvas size (Scale or Canvas mode), with undo.
|
||||
//!
|
||||
//! Used by the info panel's "Layer to document size" button. Pixels must be resident (the editor
|
||||
//! faults them in first) so the resample/copy is exact and a later page-in won't mismatch the size.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::raster_layer::RasterResizeMode;
|
||||
use crate::raster_store::RasterStore;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Per-keyframe state captured for undo.
|
||||
struct OldKeyframe {
|
||||
id: Uuid,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
pub struct ResizeRasterLayerAction {
|
||||
layer_id: Uuid,
|
||||
new_w: u32,
|
||||
new_h: u32,
|
||||
mode: RasterResizeMode,
|
||||
/// Read-only page-in for keyframes whose pixels aren't resident. (No incremental write exists, so
|
||||
/// resized keyframes stay resident + dirty and persist on the next full save.)
|
||||
store: RasterStore,
|
||||
/// Captured on first execute for rollback.
|
||||
old: Option<Vec<OldKeyframe>>,
|
||||
}
|
||||
|
||||
impl ResizeRasterLayerAction {
|
||||
pub fn new(layer_id: Uuid, new_w: u32, new_h: u32, mode: RasterResizeMode, store: RasterStore) -> Self {
|
||||
Self { layer_id, new_w, new_h, mode, store, old: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ResizeRasterLayerAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(AnyLayer::Raster(rl)) = document.get_layer_mut(&self.layer_id) else {
|
||||
return Err("ResizeRasterLayerAction: layer is not a raster layer".into());
|
||||
};
|
||||
let capture = self.old.is_none();
|
||||
let mut old = Vec::new();
|
||||
for kf in rl.keyframes.iter_mut() {
|
||||
// Page the keyframe in one at a time so we never hold the whole layer in memory at once.
|
||||
if kf.raw_pixels.is_empty() {
|
||||
if let Some(px) = self.store.load_pixels(kf.id) {
|
||||
kf.raw_pixels = px;
|
||||
kf.needs_fault_in = false;
|
||||
}
|
||||
}
|
||||
if capture {
|
||||
old.push(OldKeyframe { id: kf.id, width: kf.width, height: kf.height, pixels: kf.raw_pixels.clone() });
|
||||
}
|
||||
kf.resize_to(self.new_w, self.new_h, self.mode);
|
||||
}
|
||||
if capture {
|
||||
self.old = Some(old);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(AnyLayer::Raster(rl)) = document.get_layer_mut(&self.layer_id) else {
|
||||
return Err("ResizeRasterLayerAction: layer is not a raster layer".into());
|
||||
};
|
||||
if let Some(old) = &self.old {
|
||||
for o in old {
|
||||
if let Some(kf) = rl.keyframes.iter_mut().find(|kf| kf.id == o.id) {
|
||||
kf.width = o.width;
|
||||
kf.height = o.height;
|
||||
kf.raw_pixels = o.pixels.clone();
|
||||
kf.proxy = None;
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
match self.mode {
|
||||
RasterResizeMode::Scale => "Scale raster layer".into(),
|
||||
RasterResizeMode::Canvas => "Resize raster canvas".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Resize-text-box action
|
||||
//!
|
||||
//! Updates a text layer's box origin and dimensions (which changes the wrap
|
||||
//! width, so parley re-wraps the text). One undoable step.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use kurbo::Point;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct ResizeTextBoxAction {
|
||||
layer_id: Uuid,
|
||||
new_origin: Point,
|
||||
new_width: f64,
|
||||
new_height: f64,
|
||||
old: Option<(Point, f64, f64)>,
|
||||
}
|
||||
|
||||
impl ResizeTextBoxAction {
|
||||
pub fn new(layer_id: Uuid, new_origin: Point, new_width: f64, new_height: f64) -> Self {
|
||||
Self { layer_id, new_origin, new_width, new_height, old: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ResizeTextBoxAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let AnyLayer::Text(text_layer) = layer else {
|
||||
return Err("ResizeTextBoxAction target is not a text layer".to_string());
|
||||
};
|
||||
if self.old.is_none() {
|
||||
self.old = Some((text_layer.box_origin, text_layer.box_width, text_layer.box_height));
|
||||
}
|
||||
text_layer.box_origin = self.new_origin;
|
||||
text_layer.box_width = self.new_width.max(1.0);
|
||||
text_layer.box_height = self.new_height.max(1.0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some((origin, w, h)) = self.old else { return Ok(()) };
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
if let AnyLayer::Text(text_layer) = layer {
|
||||
text_layer.box_origin = origin;
|
||||
text_layer.box_width = w;
|
||||
text_layer.box_height = h;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Resize text box".to_string()
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
//! with undo/redo support.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::document::{Document, HdrOutputMode};
|
||||
use crate::shape::ShapeColor;
|
||||
|
||||
/// Individual property change for a document
|
||||
@@ -15,6 +15,7 @@ pub enum DocumentPropertyChange {
|
||||
Duration(f64),
|
||||
Framerate(f64),
|
||||
BackgroundColor(ShapeColor),
|
||||
HdrOutputMode(HdrOutputMode),
|
||||
}
|
||||
|
||||
/// Stored old value for undo (either f64 or color)
|
||||
@@ -22,6 +23,7 @@ pub enum DocumentPropertyChange {
|
||||
enum OldValue {
|
||||
F64(f64),
|
||||
Color(ShapeColor),
|
||||
Hdr(HdrOutputMode),
|
||||
}
|
||||
|
||||
/// Action that sets a property on the document
|
||||
@@ -72,6 +74,14 @@ impl SetDocumentPropertiesAction {
|
||||
old_value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new action to set the HDR→SDR output mode
|
||||
pub fn set_hdr_output_mode(mode: HdrOutputMode) -> Self {
|
||||
Self {
|
||||
property: DocumentPropertyChange::HdrOutputMode(mode),
|
||||
old_value: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetDocumentPropertiesAction {
|
||||
@@ -83,6 +93,7 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(_) => OldValue::F64(document.duration),
|
||||
DocumentPropertyChange::Framerate(_) => OldValue::F64(document.framerate),
|
||||
DocumentPropertyChange::BackgroundColor(_) => OldValue::Color(document.background_color),
|
||||
DocumentPropertyChange::HdrOutputMode(_) => OldValue::Hdr(document.hdr_output_mode),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -92,6 +103,7 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(v) => document.duration = *v,
|
||||
DocumentPropertyChange::Framerate(v) => document.framerate = *v,
|
||||
DocumentPropertyChange::BackgroundColor(c) => document.background_color = *c,
|
||||
DocumentPropertyChange::HdrOutputMode(m) => document.hdr_output_mode = *m,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -106,11 +118,15 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(_) => document.duration = v,
|
||||
DocumentPropertyChange::Framerate(_) => document.framerate = v,
|
||||
DocumentPropertyChange::BackgroundColor(_) => {}
|
||||
DocumentPropertyChange::HdrOutputMode(_) => {}
|
||||
}
|
||||
}
|
||||
Some(OldValue::Color(c)) => {
|
||||
document.background_color = *c;
|
||||
}
|
||||
Some(OldValue::Hdr(m)) => {
|
||||
document.hdr_output_mode = *m;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(())
|
||||
@@ -123,6 +139,7 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(_) => "duration",
|
||||
DocumentPropertyChange::Framerate(_) => "framerate",
|
||||
DocumentPropertyChange::BackgroundColor(_) => "background color",
|
||||
DocumentPropertyChange::HdrOutputMode(_) => "HDR output mode",
|
||||
};
|
||||
format!("Set {}", property_name)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Set-text-content action
|
||||
//!
|
||||
//! Replaces a text layer's [`TextContent`] (text string, font size, color, family,
|
||||
//! alignment) as one undoable step. Used both by in-place editing (text changes)
|
||||
//! and the info panel (style changes).
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::text_layer::TextContent;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct SetTextContentAction {
|
||||
layer_id: Uuid,
|
||||
new: TextContent,
|
||||
old: Option<TextContent>,
|
||||
}
|
||||
|
||||
impl SetTextContentAction {
|
||||
pub fn new(layer_id: Uuid, new: TextContent) -> Self {
|
||||
Self { layer_id, new, old: None }
|
||||
}
|
||||
|
||||
/// Construct with an explicit `old` value. Used by in-place editing, which mutates
|
||||
/// the document live for preview and then records one undoable step capturing the
|
||||
/// content as it was *before* editing began.
|
||||
pub fn with_old(layer_id: Uuid, old: TextContent, new: TextContent) -> Self {
|
||||
Self { layer_id, new, old: Some(old) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetTextContentAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let AnyLayer::Text(text_layer) = layer else {
|
||||
return Err("SetTextContentAction target is not a text layer".to_string());
|
||||
};
|
||||
if self.old.is_none() {
|
||||
self.old = Some(text_layer.content.clone());
|
||||
}
|
||||
text_layer.content = self.new.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(old) = self.old.clone() else { return Ok(()) };
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
if let AnyLayer::Text(text_layer) = layer {
|
||||
text_layer.content = old;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Edit text".to_string()
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,7 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
AnyLayer::Raster(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
AnyLayer::Text(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
};
|
||||
|
||||
let instance = clip_instances
|
||||
@@ -233,7 +234,7 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
return Err("Cannot split clip instances on group layers".to_string());
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
return Err("Cannot split clip instances on group layers".to_string());
|
||||
}
|
||||
}
|
||||
@@ -294,8 +295,8 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
// Group layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances, nothing to rollback
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
// Raster/text layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,6 +101,7 @@ impl Action for TransformClipInstancesAction {
|
||||
AnyLayer::Effect(_) => {}
|
||||
AnyLayer::Group(_) => {}
|
||||
AnyLayer::Raster(_) => {}
|
||||
AnyLayer::Text(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -140,6 +141,7 @@ impl Action for TransformClipInstancesAction {
|
||||
AnyLayer::Effect(_) => {}
|
||||
AnyLayer::Group(_) => {}
|
||||
AnyLayer::Raster(_) => {}
|
||||
AnyLayer::Text(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -138,6 +139,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -182,6 +184,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let instance = clip_instances.iter()
|
||||
@@ -275,6 +278,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Apply trims
|
||||
@@ -315,6 +319,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Restore original trim values
|
||||
|
||||
@@ -62,6 +62,10 @@ pub enum MediaKind {
|
||||
/// the keyframe id). Decoded eagerly on load and shown while the full-res pixels
|
||||
/// page in, so cold scrubs don't flash blank. See `raster_proxy_media_id`.
|
||||
RasterProxy = 6,
|
||||
/// An embedded font file (TTF/OTF) used by a text layer (keyed by a content hash
|
||||
/// of the bytes so identical fonts dedupe). Registered into the font collection
|
||||
/// on load so documents render faithfully on machines lacking the font.
|
||||
Font = 7,
|
||||
}
|
||||
|
||||
impl MediaKind {
|
||||
@@ -74,6 +78,7 @@ impl MediaKind {
|
||||
4 => Some(Self::Waveform),
|
||||
5 => Some(Self::Thumbnail),
|
||||
6 => Some(Self::RasterProxy),
|
||||
7 => Some(Self::Font),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -374,7 +379,11 @@ impl BeamArchive {
|
||||
let rows = stmt
|
||||
.query_map([&id_bytes], |r| r.get::<_, Vec<u8>>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut out = Vec::with_capacity(info.total_len as usize);
|
||||
// `total_len` is an untrusted DB field; cap the preallocation so a corrupt/oversized
|
||||
// value can't trigger a multi-GB eager allocation (or, on 32-bit, a truncated `as usize`).
|
||||
// The Vec still grows to fit the actual chunk bytes regardless.
|
||||
const PREALLOC_CAP: u64 = 64 * 1024 * 1024;
|
||||
let mut out = Vec::with_capacity(info.total_len.min(PREALLOC_CAP) as usize);
|
||||
for row in rows {
|
||||
out.extend_from_slice(&row.map_err(map_sql)?);
|
||||
}
|
||||
|
||||
@@ -122,6 +122,7 @@ impl VectorClip {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
for ci in clip_instances {
|
||||
// Compute end position of this clip instance in beats
|
||||
@@ -223,6 +224,17 @@ impl VectorClip {
|
||||
Some(existing) => existing.union(transformed_bounds),
|
||||
});
|
||||
}
|
||||
} else if let AnyLayer::Text(text_layer) = &layer_node.data {
|
||||
// Text layers contribute their box bounds (so a text-only clip is
|
||||
// selectable/draggable, not a degenerate point).
|
||||
let r = Rect::from_origin_size(
|
||||
text_layer.box_origin,
|
||||
(text_layer.box_width, text_layer.box_height),
|
||||
);
|
||||
combined_bounds = Some(match combined_bounds {
|
||||
None => r,
|
||||
Some(existing) => existing.union(r),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -62,6 +62,7 @@ impl ClipboardLayerType {
|
||||
AnyLayer::Effect(_) => ClipboardLayerType::Effect,
|
||||
AnyLayer::Group(_) => ClipboardLayerType::Vector,
|
||||
AnyLayer::Raster(_) => ClipboardLayerType::Vector,
|
||||
AnyLayer::Text(_) => ClipboardLayerType::Vector,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,6 +450,13 @@ fn regen_any_layer(layer: &AnyLayer, id_map: &mut HashMap<Uuid, Uuid>) -> AnyLay
|
||||
nl.layer.id = new_layer_id;
|
||||
AnyLayer::Raster(nl)
|
||||
}
|
||||
AnyLayer::Text(tl) => {
|
||||
let new_layer_id = Uuid::new_v4();
|
||||
id_map.insert(tl.layer.id, new_layer_id);
|
||||
let mut nl = tl.clone();
|
||||
nl.layer.id = new_layer_id;
|
||||
AnyLayer::Text(nl)
|
||||
}
|
||||
AnyLayer::Group(gl) => {
|
||||
let new_layer_id = Uuid::new_v4();
|
||||
id_map.insert(gl.layer.id, new_layer_id);
|
||||
|
||||
@@ -145,6 +145,26 @@ pub enum TimelineMode {
|
||||
Frames,
|
||||
}
|
||||
|
||||
/// How super-white (HDR) values are mapped to the SDR display/export output at the final
|
||||
/// linear→sRGB encode. SDR content sits in [0,1] and is unaffected by either mode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum HdrOutputMode {
|
||||
/// Hard-clip values above 1.0 (the historical behaviour). SDR-exact; HDR highlights blow out.
|
||||
#[default]
|
||||
Clip,
|
||||
/// Roll highlights above a knee smoothly toward 1.0 to recover detail. Slightly dims near-white.
|
||||
HighlightRolloff,
|
||||
}
|
||||
|
||||
impl HdrOutputMode {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
HdrOutputMode::Clip => "Clip",
|
||||
HdrOutputMode::HighlightRolloff => "Highlight rolloff",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asset category for folder tree access
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AssetCategory {
|
||||
@@ -244,6 +264,10 @@ pub struct Document {
|
||||
#[serde(default)]
|
||||
pub timeline_mode: TimelineMode,
|
||||
|
||||
/// How HDR (super-white) values are mapped to the SDR output at the final encode.
|
||||
#[serde(default)]
|
||||
pub hdr_output_mode: HdrOutputMode,
|
||||
|
||||
/// Current UI layout state (serialized for save/load)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ui_layout: Option<LayoutNode>,
|
||||
@@ -278,6 +302,7 @@ impl Default for Document {
|
||||
ml
|
||||
},
|
||||
duration: 10.0,
|
||||
hdr_output_mode: HdrOutputMode::default(),
|
||||
root: GraphicsObject::default(),
|
||||
vector_clips: HashMap::new(),
|
||||
video_clips: HashMap::new(),
|
||||
@@ -464,8 +489,8 @@ impl Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances
|
||||
crate::layer::AnyLayer::Raster(_) | crate::layer::AnyLayer::Text(_) => {
|
||||
// Raster and text layers don't have clip instances
|
||||
}
|
||||
crate::layer::AnyLayer::Group(group) => {
|
||||
// Recurse into group children to find their clip instance endpoints
|
||||
@@ -505,8 +530,8 @@ impl Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances
|
||||
crate::layer::AnyLayer::Raster(_) | crate::layer::AnyLayer::Text(_) => {
|
||||
// Raster and text layers don't have clip instances
|
||||
}
|
||||
crate::layer::AnyLayer::Group(g) => {
|
||||
process_group_children(&g.children, doc, max_end, calc_end);
|
||||
@@ -912,6 +937,7 @@ impl Document {
|
||||
AnyLayer::Effect(effect) => &effect.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let instance = instances.iter().find(|inst| &inst.id == instance_id)?;
|
||||
@@ -952,6 +978,7 @@ impl Document {
|
||||
AnyLayer::Effect(effect) => &effect.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
for instance in instances {
|
||||
@@ -1014,6 +1041,7 @@ impl Document {
|
||||
AnyLayer::Vector(_) => return Some(desired_start), // Shouldn't reach here
|
||||
AnyLayer::Group(_) => return Some(desired_start), // Groups don't have own clips
|
||||
AnyLayer::Raster(_) => return Some(desired_start), // Raster layers don't have own clips
|
||||
AnyLayer::Text(_) => return Some(desired_start), // Text layers don't have own clips
|
||||
};
|
||||
|
||||
let mut occupied_ranges: Vec<(f64, f64, Uuid)> = Vec::new();
|
||||
@@ -1109,6 +1137,7 @@ impl Document {
|
||||
AnyLayer::Vector(v) => &v.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
// Collect non-group clip ranges
|
||||
@@ -1180,6 +1209,7 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
for other in instances {
|
||||
@@ -1228,6 +1258,7 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let mut nearest_start = f64::MAX;
|
||||
@@ -1275,6 +1306,7 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let mut nearest_end = 0.0;
|
||||
|
||||
@@ -265,6 +265,84 @@ impl VideoCodec {
|
||||
}
|
||||
}
|
||||
|
||||
/// YUV color range for the encoded video (currently H.264). Limited/TV (16–235) is what nearly
|
||||
/// every player assumes; Full/PC (0–255) keeps a bit more precision but only looks right in players
|
||||
/// that honor the full-range tag — so Limited is the safe default.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ColorRange {
|
||||
Limited,
|
||||
Full,
|
||||
}
|
||||
|
||||
impl Default for ColorRange {
|
||||
fn default() -> Self { ColorRange::Limited }
|
||||
}
|
||||
|
||||
impl ColorRange {
|
||||
pub fn is_full(&self) -> bool { matches!(self, ColorRange::Full) }
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
ColorRange::Limited => "Limited (TV, 16–235)",
|
||||
ColorRange::Full => "Full (PC, 0–255)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// HDR output mode for video export. SDR encodes BT.709 8-bit as before; the HDR modes encode
|
||||
/// 10-bit BT.2020 with the PQ (HDR10) or HLG transfer, preserving super-white highlights from the
|
||||
/// linear compositor. HDR requires a 10-bit codec (HEVC Main10) — the exporter forces H.265.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum HdrExportMode {
|
||||
#[default]
|
||||
Sdr,
|
||||
/// PQ (SMPTE ST 2084) — HDR10. Graphics white at 203 nits (matches the compositor convention).
|
||||
Pq,
|
||||
/// HLG (ARIB STD-B67) — broadcast HDR, also displayable as SDR.
|
||||
Hlg,
|
||||
}
|
||||
|
||||
impl HdrExportMode {
|
||||
pub fn is_hdr(&self) -> bool { !matches!(self, HdrExportMode::Sdr) }
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
HdrExportMode::Sdr => "SDR (BT.709, 8-bit)",
|
||||
HdrExportMode::Pq => "HDR10 / PQ (BT.2020, 10-bit)",
|
||||
HdrExportMode::Hlg => "HLG (BT.2020, 10-bit)",
|
||||
}
|
||||
}
|
||||
/// FFmpeg transfer-characteristic name for the color tags.
|
||||
pub fn transfer_name(&self) -> &'static str {
|
||||
match self {
|
||||
HdrExportMode::Sdr => "bt709",
|
||||
HdrExportMode::Pq => "smpte2084",
|
||||
HdrExportMode::Hlg => "arib-std-b67",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the document is fit into the export frame when the export resolution's aspect ratio differs
|
||||
/// from the document's. Applied as the export `base_transform` (document space → export pixels).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum ExportFitMode {
|
||||
/// Scale each axis independently to fill the frame — distorts when aspects differ.
|
||||
Stretch,
|
||||
/// Scale uniformly to fit, centered, with black bars (letterbox/pillarbox). Preserves aspect.
|
||||
#[default]
|
||||
Letterbox,
|
||||
/// Scale uniformly to fill, centered, cropping the overflow. Preserves aspect, no bars.
|
||||
Crop,
|
||||
}
|
||||
|
||||
impl ExportFitMode {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
ExportFitMode::Stretch => "Stretch (distort to fill)",
|
||||
ExportFitMode::Letterbox => "Letterbox (fit, black bars)",
|
||||
ExportFitMode::Crop => "Crop (fill, trim edges)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Video quality presets
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum VideoQuality {
|
||||
@@ -322,6 +400,18 @@ pub struct VideoExportSettings {
|
||||
/// Video quality
|
||||
pub quality: VideoQuality,
|
||||
|
||||
/// YUV color range (H.264 only; ignored by other codecs).
|
||||
#[serde(default)]
|
||||
pub color_range: ColorRange,
|
||||
|
||||
/// HDR output mode. HDR forces 10-bit HEVC (BT.2020 + PQ/HLG); SDR is the default.
|
||||
#[serde(default)]
|
||||
pub hdr: HdrExportMode,
|
||||
|
||||
/// How the document is fit into the export frame when aspect ratios differ (default Letterbox).
|
||||
#[serde(default)]
|
||||
pub fit: ExportFitMode,
|
||||
|
||||
/// Audio settings (None = no audio)
|
||||
pub audio: Option<AudioExportSettings>,
|
||||
|
||||
@@ -340,6 +430,9 @@ impl Default for VideoExportSettings {
|
||||
height: None,
|
||||
framerate: 60.0,
|
||||
quality: VideoQuality::High,
|
||||
color_range: ColorRange::Limited,
|
||||
hdr: HdrExportMode::Sdr,
|
||||
fit: ExportFitMode::Letterbox,
|
||||
audio: Some(AudioExportSettings::high_quality_aac()),
|
||||
start_time: 0.0,
|
||||
end_time: 60.0,
|
||||
@@ -431,11 +524,14 @@ pub struct ImageExportSettings {
|
||||
/// When false, the image is composited onto an opaque background before encoding.
|
||||
/// Only meaningful for formats that support alpha (PNG, WebP).
|
||||
pub allow_transparency: bool,
|
||||
/// How the document is fit into the output frame when aspect ratios differ (default Letterbox).
|
||||
#[serde(default)]
|
||||
pub fit: ExportFitMode,
|
||||
}
|
||||
|
||||
impl Default for ImageExportSettings {
|
||||
fn default() -> Self {
|
||||
Self { format: ImageFormat::Png, time: 0.0, width: None, height: None, quality: 90, allow_transparency: false }
|
||||
Self { format: ImageFormat::Png, time: 0.0, width: None, height: None, quality: 90, allow_transparency: false, fit: ExportFitMode::Letterbox }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,21 @@ fn thumbnail_media_id(clip_id: Uuid) -> Uuid {
|
||||
Uuid::from_u128(clip_id.as_u128() ^ SENTINEL)
|
||||
}
|
||||
|
||||
/// Content-hash id for an embedded font row, so identical font files dedupe to one
|
||||
/// row regardless of which / how many text layers use them. A 128-bit id is built
|
||||
/// from two salted 64-bit hashes of the bytes.
|
||||
fn font_media_id(bytes: &[u8]) -> Uuid {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h1 = std::collections::hash_map::DefaultHasher::new();
|
||||
bytes.hash(&mut h1);
|
||||
let mut h2 = std::collections::hash_map::DefaultHasher::new();
|
||||
0xF0E1_D2C3_B4A5_9687u64.hash(&mut h2);
|
||||
bytes.hash(&mut h2);
|
||||
let hi = h1.finish() as u128;
|
||||
let lo = h2.finish() as u128;
|
||||
Uuid::from_u128((hi << 64) | lo)
|
||||
}
|
||||
|
||||
/// Derived id for a raster keyframe's low-res proxy row (distinct from the keyframe's
|
||||
/// own full-res `Raster` row, which is keyed by the raw keyframe id).
|
||||
fn raster_proxy_media_id(kf_id: Uuid) -> Uuid {
|
||||
@@ -535,6 +550,32 @@ pub fn save_beam(
|
||||
}
|
||||
let _ = image_count;
|
||||
|
||||
// --- embedded fonts -> media rows (Font), keyed by content hash so identical
|
||||
// fonts dedupe. Embed every non-bundled family used by a text layer so the
|
||||
// document renders faithfully on machines lacking the font. The bundled
|
||||
// three ship with the app and are never embedded. ---
|
||||
{
|
||||
use crate::layer::AnyLayer;
|
||||
let mut families: HashSet<String> = HashSet::new();
|
||||
for layer in document.all_layers() {
|
||||
if let AnyLayer::Text(tl) = layer {
|
||||
let fam = &tl.content.font_family;
|
||||
if !fam.is_empty() && !crate::fonts::is_bundled(fam) {
|
||||
families.insert(fam.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for fam in families {
|
||||
if let Some(bytes) = crate::fonts::family_font_bytes(&fam) {
|
||||
let id = font_media_id(&bytes);
|
||||
if !txn.media_exists(id)? {
|
||||
txn.put_media_packed(id, MediaKind::Font, &fam, &bytes, MediaMeta::default())?;
|
||||
}
|
||||
live_media.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- orphan cleanup: drop media for removed clips/keyframes ---
|
||||
let removed = txn.retain_media(&live_media)?;
|
||||
|
||||
@@ -598,6 +639,17 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
eprintln!("📊 [LOAD_BEAM] Starting load_beam() (SQLite container)...");
|
||||
|
||||
let archive = BeamArchive::open(path)?;
|
||||
|
||||
// Register document-embedded fonts into the runtime font collection so text
|
||||
// layers referencing them render faithfully even if the host lacks the font.
|
||||
if let Ok(font_ids) = archive.media_ids_of_kind(MediaKind::Font) {
|
||||
for id in font_ids {
|
||||
if let Ok(bytes) = archive.read_media_full(id) {
|
||||
crate::fonts::register_embedded(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let json = archive.get_project_json()?;
|
||||
let beam_project: BeamProject = serde_json::from_str(&json)
|
||||
.map_err(|e| format!("Failed to deserialize project.json: {}", e))?;
|
||||
|
||||
@@ -15,7 +15,9 @@ pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "mov", "avi", "mkv", "webm", "m4v
|
||||
/// Supported MIDI file extensions
|
||||
pub const MIDI_EXTENSIONS: &[&str] = &["mid", "midi"];
|
||||
|
||||
// Note: SVG import deferred to future task
|
||||
/// Supported vector file extensions (imported as a new vector layer, not an asset)
|
||||
pub const VECTOR_EXTENSIONS: &[&str] = &["svg"];
|
||||
|
||||
// Note: .beam project files handled separately in file save/load feature
|
||||
|
||||
/// File type categories for import routing
|
||||
@@ -25,6 +27,7 @@ pub enum FileType {
|
||||
Audio,
|
||||
Video,
|
||||
Midi,
|
||||
Vector,
|
||||
}
|
||||
|
||||
/// Detect file type from extension string
|
||||
@@ -53,6 +56,9 @@ pub fn get_file_type(extension: &str) -> Option<FileType> {
|
||||
if MIDI_EXTENSIONS.contains(&ext.as_str()) {
|
||||
return Some(FileType::Midi);
|
||||
}
|
||||
if VECTOR_EXTENSIONS.contains(&ext.as_str()) {
|
||||
return Some(FileType::Vector);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -65,6 +71,7 @@ pub fn all_supported_extensions() -> Vec<&'static str> {
|
||||
all.extend_from_slice(AUDIO_EXTENSIONS);
|
||||
all.extend_from_slice(VIDEO_EXTENSIONS);
|
||||
all.extend_from_slice(MIDI_EXTENSIONS);
|
||||
all.extend_from_slice(VECTOR_EXTENSIONS);
|
||||
all
|
||||
}
|
||||
|
||||
@@ -90,7 +97,8 @@ mod tests {
|
||||
assert_eq!(get_file_type("midi"), Some(FileType::Midi));
|
||||
|
||||
assert_eq!(get_file_type("unknown"), None);
|
||||
assert_eq!(get_file_type("svg"), None); // SVG deferred
|
||||
assert_eq!(get_file_type("svg"), Some(FileType::Vector));
|
||||
assert_eq!(get_file_type("SVG"), Some(FileType::Vector));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
//! Font registry + text layout for text layers.
|
||||
//!
|
||||
//! Wraps a thread-local parley [`FontContext`]/[`LayoutContext`]. Three fonts are
|
||||
//! bundled (serif, sans-serif, monospaced) so text renders deterministically even
|
||||
//! offline; system fonts are also enumerated (parley's fontique source) and
|
||||
//! document-embedded fonts can be registered at load time (see `file_io`).
|
||||
//!
|
||||
//! The same `linebender_resource_handle` crate (0.1.1) backs both vello's
|
||||
//! `peniko::FontData` and parley's `FontData`, so a glyph run's `run.font()` can be
|
||||
//! handed straight to `vello::Scene::draw_glyphs` with no conversion.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use parley::{
|
||||
Alignment, AlignmentOptions, FontContext, FontFamily, FontFamilyName, Layout, LayoutContext,
|
||||
PositionedLayoutItem, StyleProperty,
|
||||
};
|
||||
use vello::peniko::Blob;
|
||||
|
||||
use crate::text_layer::{TextAlign, TextContent};
|
||||
|
||||
// ── Bundled fonts (SIL OFL; vendored under assets/fonts) ─────────────────────
|
||||
static BUNDLED_SANS: &[u8] = include_bytes!("../assets/fonts/LiberationSans-Regular.ttf");
|
||||
static BUNDLED_SERIF: &[u8] = include_bytes!("../assets/fonts/LiberationSerif-Regular.ttf");
|
||||
static BUNDLED_MONO: &[u8] = include_bytes!("../assets/fonts/LiberationMono-Regular.ttf");
|
||||
|
||||
/// Parley requires a brush type, but glyph color is applied by vello at draw time,
|
||||
/// so we use a zero-sized placeholder.
|
||||
#[derive(Clone, Copy, PartialEq, Default, Debug)]
|
||||
pub struct NoBrush;
|
||||
|
||||
struct FontStore {
|
||||
fcx: FontContext,
|
||||
lcx: LayoutContext<NoBrush>,
|
||||
/// Registered family names of the three bundled fonts (sans, serif, mono).
|
||||
bundled: Vec<String>,
|
||||
/// The default family (bundled sans-serif), used when `font_family` is empty.
|
||||
default_family: String,
|
||||
}
|
||||
|
||||
impl FontStore {
|
||||
fn new() -> Self {
|
||||
let mut fcx = FontContext::new();
|
||||
let mut bundled = Vec::new();
|
||||
for bytes in [BUNDLED_SANS, BUNDLED_SERIF, BUNDLED_MONO] {
|
||||
let blob = Blob::new(Arc::new(bytes) as Arc<dyn AsRef<[u8]> + Send + Sync>);
|
||||
for (family_id, _) in fcx.collection.register_fonts(blob, None) {
|
||||
if let Some(name) = fcx.collection.family_name(family_id) {
|
||||
let name = name.to_string();
|
||||
if !bundled.contains(&name) {
|
||||
bundled.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let default_family = bundled.first().cloned().unwrap_or_else(|| "sans-serif".to_string());
|
||||
Self { fcx, lcx: LayoutContext::new(), bundled, default_family }
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STORE: RefCell<FontStore> = RefCell::new(FontStore::new());
|
||||
}
|
||||
|
||||
/// The default family name (bundled sans-serif), used when a text layer's
|
||||
/// `font_family` is empty.
|
||||
pub fn default_family() -> String {
|
||||
STORE.with(|s| s.borrow().default_family.clone())
|
||||
}
|
||||
|
||||
/// Whether `family` is one of the three bundled families (which therefore must
|
||||
/// never be embedded into a `.beam`).
|
||||
pub fn is_bundled(family: &str) -> bool {
|
||||
STORE.with(|s| s.borrow().bundled.iter().any(|f| f == family))
|
||||
}
|
||||
|
||||
/// True if a shorter word-prefix of `name` is itself a family in `set` — i.e. `name`
|
||||
/// is a variant of a base family (e.g. "Noto Sans Arabic" when "Noto Sans" exists).
|
||||
/// Used to collapse the many script/region-specific fonts (mostly Noto) into their
|
||||
/// base family in the picker; parley's fallback still resolves the right script font
|
||||
/// automatically when rendering non-Latin text.
|
||||
fn is_variant_of_listed_base(name: &str, set: &std::collections::HashSet<&str>) -> bool {
|
||||
let words: Vec<&str> = name.split(' ').collect();
|
||||
for k in 1..words.len() {
|
||||
if set.contains(words[..k].join(" ").as_str()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Available family names for the info-panel picker: the three bundled families first,
|
||||
/// then a consolidated, alphabetical list of system families — script/region variants
|
||||
/// whose base family is present are dropped (monospace variants are kept).
|
||||
pub fn families() -> Vec<String> {
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
|
||||
let mut system: Vec<String> =
|
||||
s.fcx.collection.family_names().map(|n| n.to_string()).collect();
|
||||
system.sort();
|
||||
system.dedup();
|
||||
let set: std::collections::HashSet<&str> = system.iter().map(|x| x.as_str()).collect();
|
||||
|
||||
let mut out = s.bundled.clone();
|
||||
for name in &system {
|
||||
if out.iter().any(|b| b == name) {
|
||||
continue;
|
||||
}
|
||||
// Keep base families and monospace variants; drop script/region variants
|
||||
// whose base family is already in the list.
|
||||
if name.contains("Mono") || !is_variant_of_listed_base(name, &set) {
|
||||
out.push(name.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a document-embedded font (raw TTF/OTF bytes) into the runtime font
|
||||
/// collection so text layers referencing its family resolve to it. Returns the
|
||||
/// registered family names.
|
||||
pub fn register_embedded(bytes: Vec<u8>) -> Vec<String> {
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
let blob = Blob::new(Arc::new(bytes) as Arc<dyn AsRef<[u8]> + Send + Sync>);
|
||||
let mut names = Vec::new();
|
||||
for (family_id, _) in s.fcx.collection.register_fonts(blob, None) {
|
||||
if let Some(name) = s.fcx.collection.family_name(family_id) {
|
||||
names.push(name.to_string());
|
||||
}
|
||||
}
|
||||
names
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `family` currently resolves to a registered family (bundled, system,
|
||||
/// or embedded). Used to flag "missing font" on load.
|
||||
pub fn family_available(family: &str) -> bool {
|
||||
if family.is_empty() {
|
||||
return true;
|
||||
}
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
s.fcx.collection.family_id(family).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
/// The raw bytes of the font file that `family` resolves to (for embedding into a
|
||||
/// `.beam`). Returns `None` if the family resolves to no glyphs. Lays out a single
|
||||
/// glyph and reads the resolved run's font blob (the same `linebender_resource_handle`
|
||||
/// blob vello uses).
|
||||
pub fn family_font_bytes(family: &str) -> Option<Vec<u8>> {
|
||||
let content = TextContent {
|
||||
text: "A".to_string(),
|
||||
font_family: family.to_string(),
|
||||
..TextContent::default()
|
||||
};
|
||||
with_layout(&content, 10_000.0, |layout| {
|
||||
for line in layout.lines() {
|
||||
for item in line.items() {
|
||||
if let PositionedLayoutItem::GlyphRun(run) = item {
|
||||
return Some(run.run().font().data.data().to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
// ── Background font preloading ───────────────────────────────────────────────
|
||||
//
|
||||
// Loading a family's bytes (`family_font_bytes`) is the expensive part (font file IO +
|
||||
// shaping). Doing it for the whole picker on the UI thread causes hitches, so a
|
||||
// background thread (started at app launch) loads every picker family's bytes ahead of
|
||||
// time into a shared map. The UI then only has to *register* them with its renderer
|
||||
// (cheap), and synchronously loads the few stragglers only if needed before they're ready.
|
||||
|
||||
struct PreloadState {
|
||||
loaded: HashMap<String, Vec<u8>>,
|
||||
started: bool,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
fn preload() -> &'static Mutex<PreloadState> {
|
||||
static P: OnceLock<Mutex<PreloadState>> = OnceLock::new();
|
||||
P.get_or_init(|| Mutex::new(PreloadState {
|
||||
loaded: HashMap::new(),
|
||||
started: false,
|
||||
done: false,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Start (once) a background thread that loads every picker font's bytes. Idempotent;
|
||||
/// safe to call every frame or from app startup.
|
||||
pub fn start_preload() {
|
||||
{
|
||||
let mut p = preload().lock().unwrap();
|
||||
if p.started {
|
||||
return;
|
||||
}
|
||||
p.started = true;
|
||||
}
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("font-preload".into())
|
||||
.spawn(|| {
|
||||
// This thread gets its own thread-local FontContext (enumerates system fonts
|
||||
// off the UI thread). Bytes are plain `Vec<u8>` (Send) handed back via the map.
|
||||
for fam in families() {
|
||||
if let Some(bytes) = family_font_bytes(&fam) {
|
||||
preload().lock().unwrap().loaded.insert(fam, bytes);
|
||||
}
|
||||
}
|
||||
preload().lock().unwrap().done = true;
|
||||
});
|
||||
}
|
||||
|
||||
/// Remove and return a preloaded font's bytes if the background thread has them ready.
|
||||
pub fn take_preloaded(family: &str) -> Option<Vec<u8>> {
|
||||
preload().lock().unwrap().loaded.remove(family)
|
||||
}
|
||||
|
||||
/// Whether the background preloader has finished loading every family.
|
||||
pub fn preload_done() -> bool {
|
||||
preload().lock().unwrap().done
|
||||
}
|
||||
|
||||
/// Caret rectangle (x0, y0, x1, y1, in layout space relative to the box origin) for
|
||||
/// `byte_index` into `content.text`, wrapped to `max_width`.
|
||||
pub fn caret_geometry(content: &TextContent, max_width: f32, byte_index: usize) -> Option<(f64, f64, f64, f64)> {
|
||||
let caret_w = (content.font_size as f32 * 0.06).max(1.0);
|
||||
with_layout(content, max_width, |layout| {
|
||||
let cur = parley::Cursor::from_byte_index(layout, byte_index, parley::Affinity::Downstream);
|
||||
let bb = cur.geometry(layout, caret_w);
|
||||
Some((bb.x0, bb.y0, bb.x1, bb.y1))
|
||||
})
|
||||
}
|
||||
|
||||
/// Selection highlight rectangles (each x0, y0, x1, y1 in layout space) for the byte
|
||||
/// range `[start, end)` into `content.text`, wrapped to `max_width`.
|
||||
pub fn selection_geometry(content: &TextContent, max_width: f32, start: usize, end: usize) -> Vec<(f64, f64, f64, f64)> {
|
||||
if start == end {
|
||||
return Vec::new();
|
||||
}
|
||||
with_layout(content, max_width, |layout| {
|
||||
let anchor = parley::Cursor::from_byte_index(layout, start, parley::Affinity::Downstream);
|
||||
let focus = parley::Cursor::from_byte_index(layout, end, parley::Affinity::Downstream);
|
||||
let sel = parley::Selection::new(anchor, focus);
|
||||
sel.geometry(layout)
|
||||
.into_iter()
|
||||
.map(|(bb, _)| (bb.x0, bb.y0, bb.x1, bb.y1))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
fn alignment_of(a: TextAlign) -> Alignment {
|
||||
match a {
|
||||
TextAlign::Left => Alignment::Left,
|
||||
TextAlign::Center => Alignment::Center,
|
||||
TextAlign::Right => Alignment::Right,
|
||||
TextAlign::Justify => Alignment::Justify,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a parley layout for `content` wrapped to `max_width` (document units),
|
||||
/// then invoke `f` with it. The layout is rebuilt on each call (v1: no cache).
|
||||
pub fn with_layout<R>(
|
||||
content: &TextContent,
|
||||
max_width: f32,
|
||||
f: impl FnOnce(&Layout<NoBrush>) -> R,
|
||||
) -> R {
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
let default_family = s.default_family.clone();
|
||||
let FontStore { fcx, lcx, .. } = s;
|
||||
|
||||
let mut builder = lcx.ranged_builder(fcx, &content.text, 1.0, true);
|
||||
builder.push_default(StyleProperty::FontSize(content.font_size as f32));
|
||||
|
||||
let family_name = if content.font_family.is_empty() {
|
||||
default_family
|
||||
} else {
|
||||
content.font_family.clone()
|
||||
};
|
||||
let family = FontFamily::Single(FontFamilyName::Named(Cow::Owned(family_name)));
|
||||
builder.push_default(StyleProperty::FontFamily(family));
|
||||
|
||||
let mut layout = builder.build(&content.text);
|
||||
layout.break_all_lines(Some(max_width));
|
||||
layout.align(alignment_of(content.align), AlignmentOptions::default());
|
||||
f(&layout)
|
||||
})
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use crate::vector_graph::VectorGraph;
|
||||
use crate::effect_layer::EffectLayer;
|
||||
use crate::object::ShapeInstance;
|
||||
use crate::raster_layer::RasterLayer;
|
||||
use crate::text_layer::TextLayer;
|
||||
use crate::shape::Shape;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@@ -31,6 +32,8 @@ pub enum LayerType {
|
||||
Group,
|
||||
/// Raster pixel-buffer painting layer
|
||||
Raster,
|
||||
/// Text layer (a single editable text box)
|
||||
Text,
|
||||
}
|
||||
|
||||
/// Common trait for all layer types
|
||||
@@ -866,6 +869,7 @@ impl GroupLayer {
|
||||
AnyLayer::Effect(l) => &l.clip_instances,
|
||||
AnyLayer::Group(_) => &[], // no nested groups
|
||||
AnyLayer::Raster(_) => &[], // raster layers have no clip instances
|
||||
AnyLayer::Text(_) => &[], // raster layers have no clip instances
|
||||
};
|
||||
for ci in instances {
|
||||
result.push((child_id, ci));
|
||||
@@ -884,6 +888,7 @@ pub enum AnyLayer {
|
||||
Effect(EffectLayer),
|
||||
Group(GroupLayer),
|
||||
Raster(RasterLayer),
|
||||
Text(TextLayer),
|
||||
}
|
||||
|
||||
impl LayerTrait for AnyLayer {
|
||||
@@ -895,6 +900,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.id(),
|
||||
AnyLayer::Group(l) => l.id(),
|
||||
AnyLayer::Raster(l) => l.id(),
|
||||
AnyLayer::Text(l) => l.id(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -906,6 +912,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.name(),
|
||||
AnyLayer::Group(l) => l.name(),
|
||||
AnyLayer::Raster(l) => l.name(),
|
||||
AnyLayer::Text(l) => l.name(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -917,6 +924,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_name(name),
|
||||
AnyLayer::Group(l) => l.set_name(name),
|
||||
AnyLayer::Raster(l) => l.set_name(name),
|
||||
AnyLayer::Text(l) => l.set_name(name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -928,6 +936,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.has_custom_name(),
|
||||
AnyLayer::Group(l) => l.has_custom_name(),
|
||||
AnyLayer::Raster(l) => l.has_custom_name(),
|
||||
AnyLayer::Text(l) => l.has_custom_name(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -939,6 +948,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_has_custom_name(custom),
|
||||
AnyLayer::Group(l) => l.set_has_custom_name(custom),
|
||||
AnyLayer::Raster(l) => l.set_has_custom_name(custom),
|
||||
AnyLayer::Text(l) => l.set_has_custom_name(custom),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -950,6 +960,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.visible(),
|
||||
AnyLayer::Group(l) => l.visible(),
|
||||
AnyLayer::Raster(l) => l.visible(),
|
||||
AnyLayer::Text(l) => l.visible(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -961,6 +972,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_visible(visible),
|
||||
AnyLayer::Group(l) => l.set_visible(visible),
|
||||
AnyLayer::Raster(l) => l.set_visible(visible),
|
||||
AnyLayer::Text(l) => l.set_visible(visible),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -972,6 +984,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.opacity(),
|
||||
AnyLayer::Group(l) => l.opacity(),
|
||||
AnyLayer::Raster(l) => l.opacity(),
|
||||
AnyLayer::Text(l) => l.opacity(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -983,6 +996,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_opacity(opacity),
|
||||
AnyLayer::Group(l) => l.set_opacity(opacity),
|
||||
AnyLayer::Raster(l) => l.set_opacity(opacity),
|
||||
AnyLayer::Text(l) => l.set_opacity(opacity),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -994,6 +1008,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.volume(),
|
||||
AnyLayer::Group(l) => l.volume(),
|
||||
AnyLayer::Raster(l) => l.volume(),
|
||||
AnyLayer::Text(l) => l.volume(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1005,6 +1020,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_volume(volume),
|
||||
AnyLayer::Group(l) => l.set_volume(volume),
|
||||
AnyLayer::Raster(l) => l.set_volume(volume),
|
||||
AnyLayer::Text(l) => l.set_volume(volume),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1016,6 +1032,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.muted(),
|
||||
AnyLayer::Group(l) => l.muted(),
|
||||
AnyLayer::Raster(l) => l.muted(),
|
||||
AnyLayer::Text(l) => l.muted(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1027,6 +1044,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_muted(muted),
|
||||
AnyLayer::Group(l) => l.set_muted(muted),
|
||||
AnyLayer::Raster(l) => l.set_muted(muted),
|
||||
AnyLayer::Text(l) => l.set_muted(muted),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1038,6 +1056,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.soloed(),
|
||||
AnyLayer::Group(l) => l.soloed(),
|
||||
AnyLayer::Raster(l) => l.soloed(),
|
||||
AnyLayer::Text(l) => l.soloed(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1049,6 +1068,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_soloed(soloed),
|
||||
AnyLayer::Group(l) => l.set_soloed(soloed),
|
||||
AnyLayer::Raster(l) => l.set_soloed(soloed),
|
||||
AnyLayer::Text(l) => l.set_soloed(soloed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1060,6 +1080,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.locked(),
|
||||
AnyLayer::Group(l) => l.locked(),
|
||||
AnyLayer::Raster(l) => l.locked(),
|
||||
AnyLayer::Text(l) => l.locked(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1071,6 +1092,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_locked(locked),
|
||||
AnyLayer::Group(l) => l.set_locked(locked),
|
||||
AnyLayer::Raster(l) => l.set_locked(locked),
|
||||
AnyLayer::Text(l) => l.set_locked(locked),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1085,6 +1107,7 @@ impl AnyLayer {
|
||||
AnyLayer::Effect(l) => &l.layer,
|
||||
AnyLayer::Group(l) => &l.layer,
|
||||
AnyLayer::Raster(l) => &l.layer,
|
||||
AnyLayer::Text(l) => &l.layer,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1097,6 +1120,7 @@ impl AnyLayer {
|
||||
AnyLayer::Effect(l) => &mut l.layer,
|
||||
AnyLayer::Group(l) => &mut l.layer,
|
||||
AnyLayer::Raster(l) => &mut l.layer,
|
||||
AnyLayer::Text(l) => &mut l.layer,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ pub mod svg_export;
|
||||
pub mod snap;
|
||||
pub mod webcam;
|
||||
pub mod raster_layer;
|
||||
pub mod text_layer;
|
||||
pub mod fonts;
|
||||
pub mod raster_store;
|
||||
pub mod brush_settings;
|
||||
pub mod brush_engine;
|
||||
|
||||
@@ -47,6 +47,21 @@ impl Transform {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Set scale + position so `content_w × content_h` is fit **uniformly and centered** within
|
||||
/// `doc_w × doc_h`, preserving aspect ratio (letterbox/pillarbox). The single shared way to
|
||||
/// place a media clip (video/image) on the document — both import paths use this so a clip
|
||||
/// looks identical however it was added. No-op for non-positive content dimensions.
|
||||
pub fn fit_centered(&mut self, content_w: f64, content_h: f64, doc_w: f64, doc_h: f64) {
|
||||
if content_w <= 0.0 || content_h <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let scale = (doc_w / content_w).min(doc_h / content_h);
|
||||
self.scale_x = scale;
|
||||
self.scale_y = scale;
|
||||
self.x = (doc_w - content_w * scale) / 2.0;
|
||||
self.y = (doc_h - content_h * scale) / 2.0;
|
||||
}
|
||||
|
||||
/// Create a transform with position
|
||||
pub fn with_position(x: f64, y: f64) -> Self {
|
||||
Self {
|
||||
|
||||
@@ -169,6 +169,57 @@ impl RasterKeyframe {
|
||||
proxy: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Change the canvas to `(new_w, new_h)`. `Scale` resamples the content (Lanczos3) to fill the
|
||||
/// new size; `Canvas` keeps the content at native resolution anchored top-left, padding with
|
||||
/// transparent (expand) or trimming (crop). No-op if the size is unchanged. If pixels aren't
|
||||
/// resident the buffer is left empty and only the declared size changes — the caller must fault
|
||||
/// pixels in first (a later load would otherwise mismatch the new size).
|
||||
pub fn resize_to(&mut self, new_w: u32, new_h: u32, mode: RasterResizeMode) {
|
||||
if new_w == 0 || new_h == 0 || (self.width == new_w && self.height == new_h) {
|
||||
return;
|
||||
}
|
||||
// Resample/recanvas the buffer only when pixels are resident. A blank keyframe (no content
|
||||
// and no store row) just takes the new declared size — there's nothing to corrupt. Paged-out
|
||||
// keyframes are loaded by the caller (ResizeRasterLayerAction) before this runs.
|
||||
if !self.raw_pixels.is_empty() {
|
||||
let old = std::mem::take(&mut self.raw_pixels);
|
||||
self.raw_pixels = match mode {
|
||||
RasterResizeMode::Scale => match image::RgbaImage::from_raw(self.width, self.height, old) {
|
||||
Some(img) => image::imageops::resize(&img, new_w, new_h, image::imageops::FilterType::Lanczos3).into_raw(),
|
||||
None => vec![0u8; (new_w as usize) * (new_h as usize) * 4],
|
||||
},
|
||||
RasterResizeMode::Canvas => {
|
||||
// Copy the old pixels into a transparent new buffer, anchored top-left (matching
|
||||
// the raster's (0,0) document anchor); right/bottom is padded or trimmed.
|
||||
let mut buf = vec![0u8; (new_w as usize) * (new_h as usize) * 4];
|
||||
let copy_w = self.width.min(new_w) as usize;
|
||||
let copy_h = self.height.min(new_h) as usize;
|
||||
let (ow, nw) = (self.width as usize, new_w as usize);
|
||||
for y in 0..copy_h {
|
||||
let src = y * ow * 4;
|
||||
let dst = y * nw * 4;
|
||||
buf[dst..dst + copy_w * 4].copy_from_slice(&old[src..src + copy_w * 4]);
|
||||
}
|
||||
buf
|
||||
}
|
||||
};
|
||||
self.proxy = None; // invalidate any downsampled proxy
|
||||
}
|
||||
self.width = new_w;
|
||||
self.height = new_h;
|
||||
self.texture_dirty = true;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// How a raster canvas resize treats existing pixels.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RasterResizeMode {
|
||||
/// Resample the content to fill the new size (changes pixel resolution).
|
||||
Scale,
|
||||
/// Keep content at native resolution, anchored top-left; pad/trim the canvas.
|
||||
Canvas,
|
||||
}
|
||||
|
||||
/// A pixel-buffer painting layer
|
||||
|
||||
@@ -221,8 +221,11 @@ fn decode_image_brush(data: &[u8]) -> Option<ImageBrush> {
|
||||
|
||||
/// A single decoded video frame ready for GPU upload, with its document-space transform.
|
||||
pub struct VideoRenderInstance {
|
||||
/// sRGB RGBA8 pixel data (straight alpha — as decoded by ffmpeg).
|
||||
/// sRGB RGBA8 pixel data (straight alpha — as decoded by ffmpeg). Empty when `gpu` is `Some`.
|
||||
pub rgba_data: Arc<Vec<u8>>,
|
||||
/// Hardware-decoded frame as GPU NV12 textures (preview path). When `Some`, the compositor
|
||||
/// samples it directly (NV12→RGB) instead of uploading `rgba_data`.
|
||||
pub gpu: Option<crate::video::GpuVideoFrame>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Affine transform that maps from video-pixel space to document space.
|
||||
@@ -366,6 +369,20 @@ pub struct CompositeRenderResult {
|
||||
/// and effects in the GPU compositor.
|
||||
///
|
||||
/// Layers are returned in bottom-to-top order for compositing.
|
||||
/// Decode-target resolution for video clips = the output (export/preview) resolution, derived from
|
||||
/// the document→output `base_transform` scale. The decoder caps this to the source's native size,
|
||||
/// so it means "decode at the size we'll actually display, never upscaling": full detail when
|
||||
/// exporting above document res (instead of upscaling a document-res frame), and cheap small frames
|
||||
/// for the canvas. Stable per render pass, so it doesn't thrash the decoder's scaler/cache.
|
||||
fn video_decode_target(document: &Document, base_transform: Affine) -> (u32, u32) {
|
||||
let c = base_transform.as_coeffs(); // [a, b, c, d, e, f]
|
||||
let sx = (c[0] * c[0] + c[1] * c[1]).sqrt();
|
||||
let sy = (c[2] * c[2] + c[3] * c[3]).sqrt();
|
||||
let w = (document.width * sx).ceil().max(1.0) as u32;
|
||||
let h = (document.height * sy).ceil().max(1.0) as u32;
|
||||
(w, h)
|
||||
}
|
||||
|
||||
pub fn render_document_for_compositing(
|
||||
document: &Document,
|
||||
base_transform: Affine,
|
||||
@@ -545,12 +562,13 @@ pub fn render_layer_isolated(
|
||||
let layer_opacity = layer.opacity();
|
||||
let mut video_mgr = video_manager.lock().unwrap();
|
||||
let mut instances = Vec::new();
|
||||
let (target_w, target_h) = video_decode_target(document, base_transform);
|
||||
|
||||
let tempo_map = document.tempo_map();
|
||||
for clip_instance in &video_layer.clip_instances {
|
||||
let Some(video_clip) = document.video_clips.get(&clip_instance.clip_id) else { continue };
|
||||
let Some(clip_time) = clip_instance.remap_time(time, video_clip.duration, tempo_map) else { continue };
|
||||
let Some(frame) = video_mgr.get_frame(&clip_instance.clip_id, clip_time) else { continue };
|
||||
let Some(frame) = video_mgr.get_frame(&clip_instance.clip_id, clip_time, target_w, target_h) else { continue };
|
||||
|
||||
// Evaluate animated transform properties.
|
||||
let anim = &video_layer.layer.animation_data;
|
||||
@@ -594,6 +612,7 @@ pub fn render_layer_isolated(
|
||||
};
|
||||
instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: frame.gpu.clone(),
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: base_transform * clip_transform * frame_to_clip,
|
||||
@@ -614,6 +633,7 @@ pub fn render_layer_isolated(
|
||||
* Affine::scale(scale);
|
||||
instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: None, // webcam frames are always CPU
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: cam_transform,
|
||||
@@ -678,6 +698,11 @@ pub fn render_layer_isolated(
|
||||
};
|
||||
}
|
||||
}
|
||||
AnyLayer::Text(text_layer) => {
|
||||
// Text composites as vector geometry (glyphs in the Vello scene).
|
||||
rendered.has_content =
|
||||
render_text_layer_to_scene(text_layer, time, &mut rendered.scene, base_transform);
|
||||
}
|
||||
}
|
||||
|
||||
rendered
|
||||
@@ -737,6 +762,57 @@ fn render_raster_layer_to_scene(
|
||||
scene.fill(Fill::NonZero, base_transform, &brush, None, &canvas_rect);
|
||||
}
|
||||
|
||||
/// Render a text layer's glyphs into a Vello scene.
|
||||
///
|
||||
/// Text is laid out with parley (wrapped to the box width) and drawn via
|
||||
/// `Scene::draw_glyphs`. The box origin offsets the whole layout; `base_transform`
|
||||
/// carries the layer/clip-instance transform and camera. Returns whether anything
|
||||
/// was drawn.
|
||||
fn render_text_layer_to_scene(
|
||||
layer: &crate::text_layer::TextLayer,
|
||||
time: f64,
|
||||
scene: &mut Scene,
|
||||
base_transform: Affine,
|
||||
) -> bool {
|
||||
let content = layer.content_at(time);
|
||||
if content.text.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let color = vello::peniko::Color::new(content.color);
|
||||
let origin = Affine::translate((layer.box_origin.x, layer.box_origin.y));
|
||||
let mut drew = false;
|
||||
crate::fonts::with_layout(content, layer.box_width as f32, |layout| {
|
||||
for line in layout.lines() {
|
||||
for item in line.items() {
|
||||
let parley::PositionedLayoutItem::GlyphRun(glyph_run) = item else { continue };
|
||||
let run = glyph_run.run();
|
||||
let font = run.font();
|
||||
let font_size = run.font_size();
|
||||
let synthesis = run.synthesis();
|
||||
let glyph_xform = synthesis
|
||||
.skew()
|
||||
.map(|angle| Affine::skew((angle as f64).to_radians().tan(), 0.0));
|
||||
drew = true;
|
||||
scene
|
||||
.draw_glyphs(font)
|
||||
.font_size(font_size)
|
||||
.brush(color)
|
||||
.transform(base_transform * origin)
|
||||
.glyph_transform(glyph_xform)
|
||||
.draw(
|
||||
Fill::NonZero,
|
||||
glyph_run.positioned_glyphs().map(|g| vello::Glyph {
|
||||
id: g.id as u32,
|
||||
x: g.x,
|
||||
y: g.y,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
drew
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Legacy Single-Scene Rendering (kept for backwards compatibility)
|
||||
// ============================================================================
|
||||
@@ -864,6 +940,11 @@ fn render_layer(
|
||||
if let Some(ex) = extract.as_deref_mut() { ex.drew_other = true; }
|
||||
render_raster_layer_to_scene(raster_layer, time, scene, base_transform);
|
||||
}
|
||||
AnyLayer::Text(text_layer) => {
|
||||
// Text is non-video content — force the Vello fallback if extracting.
|
||||
if let Some(ex) = extract.as_deref_mut() { ex.drew_other = true; }
|
||||
render_text_layer_to_scene(text_layer, time, scene, base_transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1095,8 +1176,9 @@ fn render_video_layer(
|
||||
continue; // Clip instance not active at this time
|
||||
};
|
||||
|
||||
// Get video frame from VideoManager
|
||||
let Some(frame) = video_manager.get_frame(&clip_instance.clip_id, clip_time) else {
|
||||
// Get video frame from VideoManager at the output (export/preview) resolution.
|
||||
let (target_w, target_h) = video_decode_target(document, base_transform);
|
||||
let Some(frame) = video_manager.get_frame(&clip_instance.clip_id, clip_time, target_w, target_h) else {
|
||||
continue; // Frame not available
|
||||
};
|
||||
|
||||
@@ -1244,6 +1326,7 @@ fn render_video_layer(
|
||||
if let Some(ex) = extract.as_deref_mut() {
|
||||
ex.instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: frame.gpu.clone(),
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: instance_transform * brush_transform,
|
||||
@@ -1298,6 +1381,7 @@ fn render_video_layer(
|
||||
if let Some(ex) = extract.as_deref_mut() {
|
||||
ex.instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: None, // webcam frames are always CPU
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: preview_transform,
|
||||
@@ -1321,7 +1405,7 @@ fn render_video_layer(
|
||||
/// The axis is centred on the bbox midpoint and oriented at `angle_deg` degrees
|
||||
/// (0 = left→right, 90 = top→bottom). The axis extends ± half the bbox diagonal
|
||||
/// so the gradient covers the entire shape regardless of angle.
|
||||
fn gradient_bbox_endpoints(angle_deg: f32, bbox: kurbo::Rect) -> (kurbo::Point, kurbo::Point) {
|
||||
pub(crate) fn gradient_bbox_endpoints(angle_deg: f32, bbox: kurbo::Rect) -> (kurbo::Point, kurbo::Point) {
|
||||
let cx = bbox.center().x;
|
||||
let cy = bbox.center().y;
|
||||
let dx = bbox.width();
|
||||
@@ -1877,7 +1961,9 @@ fn render_vector_content_cpu(
|
||||
render_vector_content_cpu(document, time, child, pixmap, base_transform, parent_opacity, image_cache);
|
||||
}
|
||||
}
|
||||
AnyLayer::Audio(_) | AnyLayer::Video(_) | AnyLayer::Effect(_) | AnyLayer::Raster(_) => {}
|
||||
// Text is not rendered in the tiny-skia CPU fallback (GPU path only) for v1.
|
||||
AnyLayer::Audio(_) | AnyLayer::Video(_) | AnyLayer::Effect(_) | AnyLayer::Raster(_)
|
||||
| AnyLayer::Text(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -218,3 +218,274 @@ fn cubic_to_svg_path(curve: &CubicBez) -> String {
|
||||
curve.p3.x, curve.p3.y,
|
||||
)
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Document / VectorGraph → SVG (the current model). The functions above target
|
||||
// the legacy DCEL and are kept only for the clipboard stub.
|
||||
// ===========================================================================
|
||||
|
||||
use crate::document::Document;
|
||||
use crate::gradient::{GradientExtend, GradientType, ShapeGradient};
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::shape::{Cap, FillRule, Join, ShapeColor};
|
||||
use crate::vector_graph::{FillId, VectorGraph};
|
||||
use kurbo::{BezPath, PathEl, Rect, Shape};
|
||||
|
||||
/// Serialize the document's **vector** content to a standalone SVG string, at document time `time`.
|
||||
/// Vector layers (and groups of them) only — raster/video/audio/effect layers are skipped (a later
|
||||
/// pass can rasterize them to `<image>`). Animation is a single static frame at `time`.
|
||||
pub fn document_to_svg(document: &Document, time: f64) -> String {
|
||||
let (w, h) = (document.width, document.height);
|
||||
let mut defs = String::new();
|
||||
let mut body = String::new();
|
||||
let mut grad_n = 0usize;
|
||||
|
||||
// Opaque background rect (skip if the document background is transparent).
|
||||
let bg = document.background_color;
|
||||
if bg.a > 0 {
|
||||
body.push_str(&format!(
|
||||
r#"<rect x="0" y="0" width="{w:.3}" height="{h:.3}" {}/>"#,
|
||||
fill_attrs(&bg)
|
||||
));
|
||||
}
|
||||
|
||||
for layer in &document.root.children {
|
||||
layer_to_svg(layer, time, 1.0, &mut body, &mut defs, &mut grad_n);
|
||||
}
|
||||
|
||||
format!(
|
||||
concat!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{:.0}" height="{:.0}" "#,
|
||||
r#"viewBox="0 0 {:.3} {:.3}"><defs>{}</defs>{}</svg>"#
|
||||
),
|
||||
w, h, w, h, defs, body
|
||||
)
|
||||
}
|
||||
|
||||
/// Append one layer's SVG. Recurses into groups (`<g>`); other non-vector layer types are skipped.
|
||||
fn layer_to_svg(layer: &AnyLayer, time: f64, parent_opacity: f64, body: &mut String, defs: &mut String, grad_n: &mut usize) {
|
||||
match layer {
|
||||
AnyLayer::Vector(vl) => {
|
||||
if !vl.layer.visible {
|
||||
return; // hidden layers are not rendered, so don't export them
|
||||
}
|
||||
let opacity = parent_opacity * vl.layer.opacity;
|
||||
if let Some(graph) = vl.tweened_graph_at(time) {
|
||||
let wrap = opacity < 0.999;
|
||||
if wrap {
|
||||
body.push_str(&format!(r#"<g opacity="{opacity:.4}">"#));
|
||||
}
|
||||
vector_graph_to_svg(&graph, body, defs, grad_n);
|
||||
if wrap {
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
// NOTE: placed clip instances (nested clips with their own transform) are not yet
|
||||
// exported — a refinement once loose-geometry export is verified.
|
||||
}
|
||||
AnyLayer::Group(g) => {
|
||||
if !g.layer.visible {
|
||||
return;
|
||||
}
|
||||
// Render children first; only emit the <g> wrapper if it has exportable content
|
||||
// (avoids empty groups when every child is a non-vector/hidden layer).
|
||||
let mut inner = String::new();
|
||||
for child in &g.children {
|
||||
layer_to_svg(child, time, 1.0, &mut inner, defs, grad_n);
|
||||
}
|
||||
if !inner.is_empty() {
|
||||
let opacity = parent_opacity * g.layer.opacity;
|
||||
body.push_str(&format!(r#"<g opacity="{opacity:.4}">"#));
|
||||
body.push_str(&inner);
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
// Raster/Video/Audio/Effect have no lossless vector representation — skipped this pass.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit a vector graph's fills (`<path fill>`) and stroked edges (`<path stroke>`) into `body`,
|
||||
/// accumulating any gradients into `defs`. Geometry is in document space (no per-layer transform).
|
||||
fn vector_graph_to_svg(graph: &VectorGraph, body: &mut String, defs: &mut String, grad_n: &mut usize) {
|
||||
// Fills first (drawn under strokes, matching the renderer).
|
||||
for (i, fill) in graph.fills.iter().enumerate() {
|
||||
if fill.deleted {
|
||||
continue;
|
||||
}
|
||||
let path = graph.fill_to_bezpath(FillId(i as u32));
|
||||
let d = bezpath_to_d(&path);
|
||||
if d.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rule = match fill.fill_rule {
|
||||
FillRule::NonZero => "nonzero",
|
||||
FillRule::EvenOdd => "evenodd",
|
||||
};
|
||||
|
||||
if let Some(grad) = &fill.gradient_fill {
|
||||
let id = format!("grad{}", *grad_n);
|
||||
*grad_n += 1;
|
||||
defs.push_str(&gradient_to_svg(grad, &id, path.bounding_box()));
|
||||
body.push_str(&format!(r#"<path fill="url(#{id})" fill-rule="{rule}" d="{d}"/>"#));
|
||||
} else if fill.image_fill.is_some() {
|
||||
// Image fills need <image>/<pattern> + asset embedding — skipped this (vector-only) pass.
|
||||
continue;
|
||||
} else if let Some(c) = &fill.color {
|
||||
body.push_str(&format!(r#"<path {} fill-rule="{rule}" d="{d}"/>"#, fill_attrs(c)));
|
||||
}
|
||||
}
|
||||
|
||||
// Strokes: one <path> per stroked edge (each edge may carry its own style).
|
||||
for edge in &graph.edges {
|
||||
if edge.deleted {
|
||||
continue;
|
||||
}
|
||||
if let (Some(style), Some(color)) = (&edge.stroke_style, &edge.stroke_color) {
|
||||
let d = cubic_to_svg_path(&edge.curve);
|
||||
body.push_str(&format!(
|
||||
r#"<path fill="none" {} stroke-width="{:.3}" stroke-linecap="{}" stroke-linejoin="{}" stroke-miterlimit="{:.3}" d="{d}"/>"#,
|
||||
stroke_attrs(color), style.width, cap_str(style.cap), join_str(style.join), style.miter_limit
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `<linearGradient>` / `<radialGradient>` definition matching the renderer's start/end semantics.
|
||||
fn gradient_to_svg(grad: &ShapeGradient, id: &str, bbox: Rect) -> String {
|
||||
use kurbo::Point;
|
||||
// Mirror renderer.rs: explicit world endpoints if present (radial reflects the edge through the
|
||||
// center so midpoint(start,end) == center), else derive from angle + bbox.
|
||||
let (start, end) = match (grad.start_world, grad.end_world) {
|
||||
(Some((sx, sy)), Some((ex, ey))) => match grad.kind {
|
||||
GradientType::Linear => (Point::new(sx, sy), Point::new(ex, ey)),
|
||||
GradientType::Radial => (Point::new(2.0 * sx - ex, 2.0 * sy - ey), Point::new(ex, ey)),
|
||||
},
|
||||
_ => crate::renderer::gradient_bbox_endpoints(grad.angle, bbox),
|
||||
};
|
||||
|
||||
let stops: String = grad
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| {
|
||||
format!(
|
||||
r##"<stop offset="{:.4}" stop-color="#{:02x}{:02x}{:02x}" stop-opacity="{:.4}"/>"##,
|
||||
s.position, s.color.r, s.color.g, s.color.b, s.color.a as f32 / 255.0
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let spread = match grad.extend {
|
||||
GradientExtend::Pad => "pad",
|
||||
GradientExtend::Reflect => "reflect",
|
||||
GradientExtend::Repeat => "repeat",
|
||||
};
|
||||
|
||||
match grad.kind {
|
||||
GradientType::Linear => format!(
|
||||
r#"<linearGradient id="{id}" gradientUnits="userSpaceOnUse" x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" spreadMethod="{spread}">{stops}</linearGradient>"#,
|
||||
start.x, start.y, end.x, end.y
|
||||
),
|
||||
GradientType::Radial => {
|
||||
let (cx, cy) = ((start.x + end.x) * 0.5, (start.y + end.y) * 0.5);
|
||||
let r = (((end.x - start.x).powi(2) + (end.y - start.y).powi(2)).sqrt()) * 0.5;
|
||||
format!(
|
||||
r#"<radialGradient id="{id}" gradientUnits="userSpaceOnUse" cx="{cx:.3}" cy="{cy:.3}" r="{r:.3}" spreadMethod="{spread}">{stops}</radialGradient>"#
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// kurbo `BezPath` → SVG path-data string (`M/L/Q/C/Z`).
|
||||
fn bezpath_to_d(path: &BezPath) -> String {
|
||||
let mut d = String::new();
|
||||
for el in path.elements() {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => d.push_str(&format!("M{:.3} {:.3} ", p.x, p.y)),
|
||||
PathEl::LineTo(p) => d.push_str(&format!("L{:.3} {:.3} ", p.x, p.y)),
|
||||
PathEl::QuadTo(p1, p) => d.push_str(&format!("Q{:.3} {:.3} {:.3} {:.3} ", p1.x, p1.y, p.x, p.y)),
|
||||
PathEl::CurveTo(p1, p2, p) => d.push_str(&format!(
|
||||
"C{:.3} {:.3} {:.3} {:.3} {:.3} {:.3} ",
|
||||
p1.x, p1.y, p2.x, p2.y, p.x, p.y
|
||||
)),
|
||||
PathEl::ClosePath => d.push_str("Z "),
|
||||
}
|
||||
}
|
||||
d.trim_end().to_string()
|
||||
}
|
||||
|
||||
// sRGB color → SVG attributes. Hex color + a separate `*-opacity` for max compatibility (Inkscape).
|
||||
fn fill_attrs(c: &ShapeColor) -> String {
|
||||
if c.a == 255 {
|
||||
format!(r##"fill="#{:02x}{:02x}{:02x}""##, c.r, c.g, c.b)
|
||||
} else {
|
||||
format!(r##"fill="#{:02x}{:02x}{:02x}" fill-opacity="{:.4}""##, c.r, c.g, c.b, c.a as f32 / 255.0)
|
||||
}
|
||||
}
|
||||
fn stroke_attrs(c: &ShapeColor) -> String {
|
||||
if c.a == 255 {
|
||||
format!(r##"stroke="#{:02x}{:02x}{:02x}""##, c.r, c.g, c.b)
|
||||
} else {
|
||||
format!(r##"stroke="#{:02x}{:02x}{:02x}" stroke-opacity="{:.4}""##, c.r, c.g, c.b, c.a as f32 / 255.0)
|
||||
}
|
||||
}
|
||||
fn cap_str(cap: Cap) -> &'static str {
|
||||
match cap {
|
||||
Cap::Butt => "butt",
|
||||
Cap::Round => "round",
|
||||
Cap::Square => "square",
|
||||
}
|
||||
}
|
||||
fn join_str(join: Join) -> &'static str {
|
||||
match join {
|
||||
Join::Miter => "miter",
|
||||
Join::Round => "round",
|
||||
Join::Bevel => "bevel",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod export_tests {
|
||||
use super::*;
|
||||
use crate::shape::{ShapeColor, StrokeStyle};
|
||||
use crate::vector_graph::{Direction, VectorGraph};
|
||||
use kurbo::{CubicBez, Point};
|
||||
|
||||
fn line(a: Point, b: Point) -> CubicBez {
|
||||
// Degenerate cubic representing a straight segment (matches our model).
|
||||
CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solid_triangle_fill_and_stroke() {
|
||||
let mut g = VectorGraph::new();
|
||||
let p0 = Point::new(10.0, 10.0);
|
||||
let p1 = Point::new(90.0, 10.0);
|
||||
let p2 = Point::new(50.0, 80.0);
|
||||
let v0 = g.alloc_vertex(p0);
|
||||
let v1 = g.alloc_vertex(p1);
|
||||
let v2 = g.alloc_vertex(p2);
|
||||
let stroke = Some(StrokeStyle { width: 2.0, ..Default::default() });
|
||||
let scol = Some(ShapeColor::rgb(0, 0, 0));
|
||||
let e0 = g.alloc_edge(line(p0, p1), v0, v1, stroke.clone(), scol);
|
||||
let e1 = g.alloc_edge(line(p1, p2), v1, v2, stroke.clone(), scol);
|
||||
let e2 = g.alloc_edge(line(p2, p0), v2, v0, stroke.clone(), scol);
|
||||
g.alloc_fill(
|
||||
vec![(e0, Direction::Forward), (e1, Direction::Forward), (e2, Direction::Forward)],
|
||||
ShapeColor::rgb(255, 0, 0),
|
||||
crate::shape::FillRule::NonZero,
|
||||
);
|
||||
|
||||
let mut body = String::new();
|
||||
let mut defs = String::new();
|
||||
let mut n = 0;
|
||||
vector_graph_to_svg(&g, &mut body, &mut defs, &mut n);
|
||||
|
||||
assert!(body.contains(r##"fill="#ff0000""##), "fill color missing: {body}");
|
||||
assert!(body.contains(r#"fill-rule="nonzero""#), "fill-rule missing: {body}");
|
||||
assert!(body.contains(r#"fill="none""#), "stroke path missing: {body}");
|
||||
assert!(body.contains(r#"stroke-width="2.000""#), "stroke width missing: {body}");
|
||||
assert!(defs.is_empty(), "no gradients expected: {defs}");
|
||||
// 1 fill path + 3 stroked edges = 4 <path> elements.
|
||||
assert_eq!(body.matches("<path").count(), 4, "{body}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Text layer for Lightningbeam
|
||||
//!
|
||||
//! A text layer holds a single editable text field inside a resizable box,
|
||||
//! with editable size, color, and font. Text is rendered as vector glyphs
|
||||
//! (via parley + Vello) so it composites through the same path as vector art.
|
||||
//!
|
||||
//! The text/style fields are grouped in [`TextContent`] so they can move to a
|
||||
//! per-keyframe model later without touching call sites; v1 stores a single
|
||||
//! static instance and reads it through [`TextLayer::content_at`].
|
||||
|
||||
use crate::layer::{Layer, LayerTrait, LayerType};
|
||||
use kurbo::Point;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Horizontal alignment of text within the box.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum TextAlign {
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
Justify,
|
||||
}
|
||||
|
||||
impl Default for TextAlign {
|
||||
fn default() -> Self {
|
||||
TextAlign::Left
|
||||
}
|
||||
}
|
||||
|
||||
/// The text content + styling for a text layer.
|
||||
///
|
||||
/// Grouped as its own struct so a future keyframed model can store
|
||||
/// `Vec<TextKeyframe>` of these without changing the layer's public shape.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextContent {
|
||||
/// The text string.
|
||||
pub text: String,
|
||||
/// Font size in pixels (document space).
|
||||
pub font_size: f64,
|
||||
/// Fill color, linear RGBA in 0..=1.
|
||||
pub color: [f32; 4],
|
||||
/// Logical font family name. Empty string = the bundled default font.
|
||||
pub font_family: String,
|
||||
/// Horizontal alignment within the box.
|
||||
pub align: TextAlign,
|
||||
}
|
||||
|
||||
impl Default for TextContent {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: String::new(),
|
||||
font_size: 48.0,
|
||||
color: [1.0, 1.0, 1.0, 1.0],
|
||||
font_family: String::new(),
|
||||
align: TextAlign::Left,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextContent {
|
||||
/// A stable hash of everything that affects shaped layout (everything except
|
||||
/// `color`, which only affects the brush, not glyph positions). Used to key
|
||||
/// the renderer's external parley-layout cache, including the wrap width.
|
||||
pub fn layout_hash(&self, box_width: f64) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
self.text.hash(&mut h);
|
||||
self.font_size.to_bits().hash(&mut h);
|
||||
self.font_family.hash(&mut h);
|
||||
self.align.hash(&mut h);
|
||||
box_width.to_bits().hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for TextAlign {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
(*self as u8).hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// A text layer: a single resizable text box.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TextLayer {
|
||||
/// Base layer properties (id, name, opacity, visibility, animation data, …).
|
||||
pub layer: Layer,
|
||||
/// Top-left of the text box, in layer/clip-local space.
|
||||
pub box_origin: Point,
|
||||
/// Box width in document units (drives text wrapping).
|
||||
pub box_width: f64,
|
||||
/// Box height in document units.
|
||||
pub box_height: f64,
|
||||
/// The text content + styling (single static instance for v1).
|
||||
pub content: TextContent,
|
||||
}
|
||||
|
||||
impl TextLayer {
|
||||
/// Default text-box dimensions for a freshly created layer.
|
||||
pub const DEFAULT_WIDTH: f64 = 300.0;
|
||||
pub const DEFAULT_HEIGHT: f64 = 100.0;
|
||||
|
||||
/// Create a new, empty text layer with the given name, positioned at `origin`.
|
||||
pub fn new(name: impl Into<String>, origin: Point) -> Self {
|
||||
Self {
|
||||
layer: Layer::new(LayerType::Text, name),
|
||||
box_origin: origin,
|
||||
box_width: Self::DEFAULT_WIDTH,
|
||||
box_height: Self::DEFAULT_HEIGHT,
|
||||
content: TextContent::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the active text content at `time`. v1 is static, so `time` is unused;
|
||||
/// a future keyframed model will select the active keyframe here.
|
||||
pub fn content_at(&self, _time: f64) -> &TextContent {
|
||||
&self.content
|
||||
}
|
||||
|
||||
/// Mutable access to the active text content at `time`.
|
||||
pub fn content_at_mut(&mut self, _time: f64) -> &mut TextContent {
|
||||
&mut self.content
|
||||
}
|
||||
}
|
||||
|
||||
// Delegate all LayerTrait methods to self.layer (mirrors RasterLayer).
|
||||
impl LayerTrait for TextLayer {
|
||||
fn id(&self) -> Uuid { self.layer.id }
|
||||
fn name(&self) -> &str { &self.layer.name }
|
||||
fn set_name(&mut self, name: String) { self.layer.name = name; }
|
||||
fn has_custom_name(&self) -> bool { self.layer.has_custom_name }
|
||||
fn set_has_custom_name(&mut self, custom: bool) { self.layer.has_custom_name = custom; }
|
||||
fn visible(&self) -> bool { self.layer.visible }
|
||||
fn set_visible(&mut self, visible: bool) { self.layer.visible = visible; }
|
||||
fn opacity(&self) -> f64 { self.layer.opacity }
|
||||
fn set_opacity(&mut self, opacity: f64) { self.layer.opacity = opacity; }
|
||||
fn volume(&self) -> f64 { self.layer.volume }
|
||||
fn set_volume(&mut self, volume: f64) { self.layer.volume = volume; }
|
||||
fn muted(&self) -> bool { self.layer.muted }
|
||||
fn set_muted(&mut self, muted: bool) { self.layer.muted = muted; }
|
||||
fn soloed(&self) -> bool { self.layer.soloed }
|
||||
fn set_soloed(&mut self, soloed: bool) { self.layer.soloed = soloed; }
|
||||
fn locked(&self) -> bool { self.layer.locked }
|
||||
fn set_locked(&mut self, locked: bool) { self.layer.locked = locked; }
|
||||
}
|
||||
@@ -381,7 +381,9 @@ impl Tool {
|
||||
use crate::layer::LayerType;
|
||||
match layer_type {
|
||||
None | Some(LayerType::Vector) => Tool::all(),
|
||||
Some(LayerType::Audio) | Some(LayerType::Video) => &[Tool::Select, Tool::Split],
|
||||
// The Text tool is available on audio/video/raster too: clicking the
|
||||
// stage with it there creates a new top-level text layer.
|
||||
Some(LayerType::Audio) | Some(LayerType::Video) => &[Tool::Select, Tool::Split, Tool::Text],
|
||||
Some(LayerType::Raster) => &[
|
||||
// Brush tools
|
||||
Tool::Draw, Tool::Pencil, Tool::Pen, Tool::Airbrush,
|
||||
@@ -397,9 +399,10 @@ impl Tool {
|
||||
// Transform
|
||||
Tool::Transform, Tool::Warp, Tool::Liquify,
|
||||
// Utility
|
||||
Tool::Eyedropper,
|
||||
Tool::Eyedropper, Tool::Text,
|
||||
],
|
||||
_ => &[Tool::Select],
|
||||
Some(LayerType::Text) => &[Tool::Select, Tool::Text, Tool::Transform],
|
||||
_ => &[Tool::Select, Tool::Text],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -351,6 +351,29 @@ impl VectorGraph {
|
||||
}
|
||||
}
|
||||
|
||||
/// Free any vertex no longer referenced by a non-deleted edge (e.g. after deleting a shape's
|
||||
/// edges), so stale vertices don't linger as snap targets.
|
||||
pub fn gc_isolated_vertices(&mut self) {
|
||||
let mut referenced = vec![false; self.vertices.len()];
|
||||
for e in &self.edges {
|
||||
if e.deleted {
|
||||
continue;
|
||||
}
|
||||
for v in e.vertices.iter() {
|
||||
if !v.is_none() {
|
||||
referenced[v.idx()] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let to_free: Vec<VertexId> = (0..self.vertices.len())
|
||||
.filter(|&i| !self.vertices[i].deleted && !referenced[i])
|
||||
.map(|i| VertexId(i as u32))
|
||||
.collect();
|
||||
for vid in to_free {
|
||||
self.free_vertex(vid);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Fill / hit-test queries
|
||||
// -------------------------------------------------------------------
|
||||
@@ -1302,21 +1325,26 @@ impl VectorGraph {
|
||||
/// bouncing across near-coincident duplicate edges). These are zero-area and would make
|
||||
/// `boundary_to_bezpath` render a stray hair; collapsing them yields a simple loop.
|
||||
fn collapse_boundary_spikes(&self, face: &mut Vec<(EdgeId, Direction)>) {
|
||||
let dstart = |entry: &(EdgeId, Direction)| -> Point {
|
||||
// The four control points of an entry's curve in its traversal order.
|
||||
let traversed = |entry: &(EdgeId, Direction)| -> [Point; 4] {
|
||||
let c = self.edges[entry.0.idx()].curve;
|
||||
match entry.1 {
|
||||
Direction::Forward => c.p0,
|
||||
Direction::Backward => c.p3,
|
||||
}
|
||||
};
|
||||
let dend = |entry: &(EdgeId, Direction)| -> Point {
|
||||
let c = self.edges[entry.0.idx()].curve;
|
||||
match entry.1 {
|
||||
Direction::Forward => c.p3,
|
||||
Direction::Backward => c.p0,
|
||||
Direction::Forward => [c.p0, c.p1, c.p2, c.p3],
|
||||
Direction::Backward => [c.p3, c.p2, c.p1, c.p0],
|
||||
}
|
||||
};
|
||||
const EPS: f64 = 0.5;
|
||||
// Entries i and j cancel only when j is the *exact reverse* of i — every control point of
|
||||
// j matches the mirror of i. Testing endpoints alone would also collapse a genuine
|
||||
// lens/sliver (two distinct edges that merely share near-coincident endpoints), silently
|
||||
// deleting real boundary geometry and dropping the fill.
|
||||
let reverses = |a: &(EdgeId, Direction), b: &(EdgeId, Direction)| -> bool {
|
||||
let (ca, cb) = (traversed(a), traversed(b));
|
||||
(0..4).all(|k| {
|
||||
let (p, q) = (ca[k], cb[3 - k]);
|
||||
(p.x - q.x).hypot(p.y - q.y) < EPS
|
||||
})
|
||||
};
|
||||
loop {
|
||||
let n = face.len();
|
||||
if n < 2 {
|
||||
@@ -1325,10 +1353,7 @@ impl VectorGraph {
|
||||
let mut collapsed = false;
|
||||
for i in 0..n {
|
||||
let j = (i + 1) % n;
|
||||
// entries i and j cancel when j ends back at i's start.
|
||||
let si = dstart(&face[i]);
|
||||
let ej = dend(&face[j]);
|
||||
if (si.x - ej.x).hypot(si.y - ej.y) < EPS {
|
||||
if reverses(&face[i], &face[j]) {
|
||||
let (hi, lo) = if i > j { (i, j) } else { (j, i) };
|
||||
face.remove(hi);
|
||||
face.remove(lo);
|
||||
|
||||
@@ -84,19 +84,215 @@ pub struct VideoMetadata {
|
||||
/// Video decoder with LRU frame caching
|
||||
pub struct VideoDecoder {
|
||||
source: VideoSource,
|
||||
_width: u32, // Original video width
|
||||
_height: u32, // Original video height
|
||||
output_width: u32, // Scaled output width
|
||||
output_height: u32, // Scaled output height
|
||||
native_width: u32, // Original (decoded) video width
|
||||
native_height: u32, // Original (decoded) video height
|
||||
fps: f64,
|
||||
_duration: f64,
|
||||
time_base: f64,
|
||||
stream_index: usize,
|
||||
frame_cache: LruCache<i64, Vec<u8>>, // timestamp -> RGBA data
|
||||
// Decoded RGBA keyed by (frame timestamp, output width, output height): the same source
|
||||
// frame may be requested at different sizes (preview res vs export res).
|
||||
frame_cache: LruCache<(i64, u32, u32), Vec<u8>>,
|
||||
input: Option<OwnedInput>,
|
||||
decoder: Option<ffmpeg::decoder::Video>,
|
||||
last_decoded_ts: i64, // Track the last decoded frame timestamp
|
||||
/// The `frame_ts` requested by the previous `get_frame` call. Used to detect a genuine backward
|
||||
/// jump (scrub/loop) from the request stream, which — unlike the decoded PTS — is strictly
|
||||
/// monotonic during forward playback, so it never falses on the request-vs-PTS grid mismatch.
|
||||
last_requested_ts: i64,
|
||||
keyframe_positions: Vec<i64>, // Index of keyframe timestamps for fast seeking
|
||||
/// Reused RGBA scaler, keyed by `(input format, input w, input h, output w, output h)`.
|
||||
/// Building an swscale context isn't free; a stream's frames share one input format/size and a
|
||||
/// consumer keeps one output size, so it's built once and rebuilt only when either changes.
|
||||
scaler: Option<(ffmpeg::format::Pixel, u32, u32, u32, u32, SendScaler)>,
|
||||
/// When set (and `hw_failed` is false), decode on the GPU: attach `hw_device` as the decoder's
|
||||
/// `hw_device_ctx`, decode into VAAPI surfaces, and hand each surface to `importer` to import as
|
||||
/// wgpu NV12 textures (no CPU copy). `None`/failure → the software swscale path.
|
||||
hw_device: Option<HwDeviceHandle>,
|
||||
importer: Option<Arc<dyn HwVideoImporter>>,
|
||||
/// Set if hardware decode init failed for this clip — fall back to software permanently.
|
||||
hw_failed: bool,
|
||||
}
|
||||
|
||||
/// A decoded frame: CPU RGBA (software) or GPU NV12 textures (hardware).
|
||||
enum DecodedFrame {
|
||||
Cpu { rgba: Vec<u8>, width: u32, height: u32 },
|
||||
Gpu(GpuVideoFrame),
|
||||
}
|
||||
|
||||
/// Result of processing one decoded frame against the requested target timestamp.
|
||||
enum FrameOutcome {
|
||||
/// Frame consumed; keep decoding.
|
||||
Continue,
|
||||
/// `current_frame_ts >= frame_ts` — caller should return the best frame found.
|
||||
ReachedTarget,
|
||||
/// Hardware surface import failed; caller should fall back to software.
|
||||
HwImportFailed,
|
||||
}
|
||||
|
||||
/// Process one decoded `frame`: update the best-so-far (`best_*`) toward `frame_ts`, importing a
|
||||
/// GPU surface (`gpu_out`) or swscaling to RGBA otherwise. Pulled out of the decode loop so the
|
||||
/// same logic runs both for packet-fed frames and for frames flushed out of the codec at EOF.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn process_decoded_video_frame(
|
||||
frame: &mut ffmpeg::util::frame::Video,
|
||||
decoder: &ffmpeg::decoder::Video,
|
||||
gpu_out: bool,
|
||||
hw: bool,
|
||||
out_w: u32,
|
||||
out_h: u32,
|
||||
frame_ts: i64,
|
||||
importer: Option<&Arc<dyn HwVideoImporter>>,
|
||||
scaler: &mut Option<(ffmpeg::format::Pixel, u32, u32, u32, u32, SendScaler)>,
|
||||
best_frame_data: &mut Option<Vec<u8>>,
|
||||
best_gpu: &mut Option<GpuVideoFrame>,
|
||||
best_frame_ts: &mut Option<i64>,
|
||||
last_decoded_ts: &mut i64,
|
||||
scale_time_ms: &mut u128,
|
||||
) -> Result<FrameOutcome, String> {
|
||||
use std::time::Instant;
|
||||
|
||||
// A frame with no PTS continues monotonically from the last decoded position rather than
|
||||
// snapping to 0 — treating "no timestamp" as ts=0 would look like a huge backward jump and
|
||||
// corrupt the best-frame / seek logic on streams with missing PTS.
|
||||
let current_frame_ts = frame.timestamp().unwrap_or(*last_decoded_ts + 1);
|
||||
*last_decoded_ts = current_frame_ts;
|
||||
|
||||
let is_better = match *best_frame_ts {
|
||||
None => true,
|
||||
Some(best_ts) => (current_frame_ts - frame_ts).abs() < (best_ts - frame_ts).abs(),
|
||||
};
|
||||
|
||||
if is_better {
|
||||
if gpu_out {
|
||||
// VAAPI hw frames often don't carry the stream's colour tags, so the importer would
|
||||
// mis-detect transfer/gamut. Copy the authoritative values from the codec context
|
||||
// (parsed from the bitstream) onto the frame when it left them unspecified.
|
||||
unsafe {
|
||||
use ffmpeg::ffi::*;
|
||||
let fp = frame.as_mut_ptr();
|
||||
let cp = decoder.as_ptr();
|
||||
if (*fp).color_trc == AVColorTransferCharacteristic::AVCOL_TRC_UNSPECIFIED {
|
||||
(*fp).color_trc = (*cp).color_trc;
|
||||
}
|
||||
if (*fp).color_primaries == AVColorPrimaries::AVCOL_PRI_UNSPECIFIED {
|
||||
(*fp).color_primaries = (*cp).color_primaries;
|
||||
}
|
||||
if (*fp).colorspace == AVColorSpace::AVCOL_SPC_UNSPECIFIED {
|
||||
(*fp).colorspace = (*cp).colorspace;
|
||||
}
|
||||
if (*fp).color_range == AVColorRange::AVCOL_RANGE_UNSPECIFIED {
|
||||
(*fp).color_range = (*cp).color_range;
|
||||
}
|
||||
}
|
||||
let importer = importer.unwrap();
|
||||
match unsafe { importer.import(frame.as_mut_ptr() as *mut std::ffi::c_void) } {
|
||||
Some(gpu) => {
|
||||
*best_gpu = Some(gpu);
|
||||
*best_frame_ts = Some(current_frame_ts);
|
||||
}
|
||||
None => return Ok(FrameOutcome::HwImportFailed),
|
||||
}
|
||||
} else {
|
||||
let t_scale_start = Instant::now();
|
||||
|
||||
// A hardware decoder produces VAAPI surfaces; a CPU consumer (export) downloads to
|
||||
// system memory first, then swscales like the software path.
|
||||
let downloaded;
|
||||
let src: &ffmpeg::util::frame::Video = if hw {
|
||||
let mut dl = ffmpeg::util::frame::Video::empty();
|
||||
let r = unsafe {
|
||||
ffmpeg::ffi::av_hwframe_transfer_data(dl.as_mut_ptr(), frame.as_ptr(), 0)
|
||||
};
|
||||
if r < 0 {
|
||||
return Err(format!("av_hwframe_transfer_data failed: {r}"));
|
||||
}
|
||||
downloaded = dl;
|
||||
&downloaded
|
||||
} else {
|
||||
&*frame
|
||||
};
|
||||
|
||||
// Reuse the RGBA scaler across frames; rebuild only if the input format/size or the
|
||||
// requested output size changes.
|
||||
let need_new = match scaler {
|
||||
Some((fmt, w, h, ow, oh, _)) => {
|
||||
*fmt != src.format() || *w != src.width() || *h != src.height()
|
||||
|| *ow != out_w || *oh != out_h
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if need_new {
|
||||
let ctx = ffmpeg::software::scaling::context::Context::get(
|
||||
src.format(),
|
||||
src.width(),
|
||||
src.height(),
|
||||
ffmpeg::format::Pixel::RGBA,
|
||||
out_w,
|
||||
out_h,
|
||||
ffmpeg::software::scaling::flag::Flags::BILINEAR,
|
||||
).map_err(|e| e.to_string())?;
|
||||
*scaler = Some((src.format(), src.width(), src.height(), out_w, out_h, SendScaler(ctx)));
|
||||
}
|
||||
let scaler = &mut scaler.as_mut().unwrap().5.0;
|
||||
|
||||
let mut rgb_frame = ffmpeg::util::frame::Video::empty();
|
||||
scaler.run(src, &mut rgb_frame)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Remove stride padding to create tightly packed RGBA data
|
||||
let width = out_w as usize;
|
||||
let height = out_h as usize;
|
||||
let stride = rgb_frame.stride(0);
|
||||
let row_size = width * 4; // RGBA = 4 bytes per pixel
|
||||
let source_data = rgb_frame.data(0);
|
||||
|
||||
let mut packed_data = Vec::with_capacity(row_size * height);
|
||||
for y in 0..height {
|
||||
let row_start = y * stride;
|
||||
let row_end = row_start + row_size;
|
||||
packed_data.extend_from_slice(&source_data[row_start..row_end]);
|
||||
}
|
||||
|
||||
*scale_time_ms += t_scale_start.elapsed().as_millis();
|
||||
*best_frame_data = Some(packed_data);
|
||||
*best_frame_ts = Some(current_frame_ts);
|
||||
}
|
||||
}
|
||||
|
||||
if current_frame_ts >= frame_ts {
|
||||
Ok(FrameOutcome::ReachedTarget)
|
||||
} else {
|
||||
Ok(FrameOutcome::Continue)
|
||||
}
|
||||
}
|
||||
|
||||
/// `get_format` callback for hardware decode: select VAAPI surfaces. With `hw_device_ctx` set,
|
||||
/// FFmpeg auto-allocates the frames context.
|
||||
unsafe extern "C" fn get_vaapi_format(
|
||||
_ctx: *mut ffmpeg::ffi::AVCodecContext,
|
||||
mut fmts: *const ffmpeg::ffi::AVPixelFormat,
|
||||
) -> ffmpeg::ffi::AVPixelFormat {
|
||||
while *fmts != ffmpeg::ffi::AVPixelFormat::AV_PIX_FMT_NONE {
|
||||
if *fmts == ffmpeg::ffi::AVPixelFormat::AV_PIX_FMT_VAAPI {
|
||||
return ffmpeg::ffi::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
}
|
||||
fmts = fmts.add(1);
|
||||
}
|
||||
ffmpeg::ffi::AVPixelFormat::AV_PIX_FMT_NONE
|
||||
}
|
||||
|
||||
/// `SwsContext` is `!Send` in ffmpeg-next, but a `VideoDecoder` (like its decoder/input) is only
|
||||
/// ever accessed under the `VideoManager` mutex — never concurrently — so moving it between
|
||||
/// threads is sound. The decoder/input fields rely on the same invariant.
|
||||
struct SendScaler(ffmpeg::software::scaling::context::Context);
|
||||
unsafe impl Send for SendScaler {}
|
||||
|
||||
/// Per-frame video decode tracing, gated behind `LB_VIDEO_DEBUG` (checked once). Off by
|
||||
/// default — at export frame rates these prints are a lot of locked stderr writes.
|
||||
fn video_debug() -> bool {
|
||||
static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*V.get_or_init(|| std::env::var("LB_VIDEO_DEBUG").is_ok())
|
||||
}
|
||||
|
||||
impl VideoDecoder {
|
||||
@@ -129,14 +325,12 @@ impl VideoDecoder {
|
||||
let height = decoder.height();
|
||||
let time_base = f64::from(video_stream.time_base());
|
||||
|
||||
// Calculate output dimensions (scale down if larger than max)
|
||||
let (output_width, output_height) = if let (Some(max_w), Some(max_h)) = (max_width, max_height) {
|
||||
// Calculate scale to fit within max dimensions while preserving aspect ratio
|
||||
let scale = (max_w as f32 / width as f32).min(max_h as f32 / height as f32).min(1.0);
|
||||
((width as f32 * scale) as u32, (height as f32 * scale) as u32)
|
||||
} else {
|
||||
(width, height)
|
||||
};
|
||||
// Output dimensions are now chosen per `get_frame` call (the caller's target res, capped to
|
||||
// native) rather than frozen here — so the same clip can be decoded at preview res for the
|
||||
// canvas and at full export res, and exporting above document res no longer upscales.
|
||||
// `max_width`/`max_height` are retained as an upper bound for callers that want a fixed cap
|
||||
// (e.g. thumbnails pass their thumb width per call instead).
|
||||
let _ = (max_width, max_height);
|
||||
|
||||
// Try to get duration from stream, fallback to container
|
||||
let duration = if video_stream.duration() > 0 {
|
||||
@@ -168,10 +362,8 @@ impl VideoDecoder {
|
||||
|
||||
Ok(Self {
|
||||
source,
|
||||
_width: width,
|
||||
_height: height,
|
||||
output_width,
|
||||
output_height,
|
||||
native_width: width,
|
||||
native_height: height,
|
||||
fps,
|
||||
_duration: duration,
|
||||
time_base,
|
||||
@@ -182,10 +374,31 @@ impl VideoDecoder {
|
||||
input: None,
|
||||
decoder: None,
|
||||
last_decoded_ts: -1,
|
||||
last_requested_ts: i64::MIN,
|
||||
keyframe_positions,
|
||||
scaler: None,
|
||||
hw_device: None,
|
||||
importer: None,
|
||||
hw_failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configure hardware (VAAPI) decode for this clip. The next decoder open attaches `hw_device`
|
||||
/// and decodes into VAAPI surfaces imported by `importer`. Resets any prior decoder so the new
|
||||
/// mode takes effect on the next `get_frame`.
|
||||
fn set_hardware(&mut self, hw_device: HwDeviceHandle, importer: Arc<dyn HwVideoImporter>) {
|
||||
self.hw_device = Some(hw_device);
|
||||
self.importer = Some(importer);
|
||||
self.hw_failed = false;
|
||||
self.decoder = None; // force a rebuild with hw_device_ctx
|
||||
self.input = None;
|
||||
}
|
||||
|
||||
/// Whether this decoder will hardware-decode (configured + not failed).
|
||||
fn hw_active(&self) -> bool {
|
||||
self.hw_device.is_some() && self.importer.is_some() && !self.hw_failed
|
||||
}
|
||||
|
||||
/// The source this decoder reads from (file path or packed container blob).
|
||||
pub fn source(&self) -> VideoSource {
|
||||
self.source.clone()
|
||||
@@ -201,19 +414,22 @@ impl VideoDecoder {
|
||||
self.keyframe_positions = positions;
|
||||
}
|
||||
|
||||
/// Get the output width (scaled dimensions)
|
||||
pub fn get_output_width(&self) -> u32 {
|
||||
self.output_width
|
||||
/// The output size for a requested target: the target capped to native resolution, preserving
|
||||
/// aspect ratio (never upscale beyond native — there's no detail to invent).
|
||||
fn capped_output(&self, target_w: u32, target_h: u32) -> (u32, u32) {
|
||||
let (nw, nh) = (self.native_width as f32, self.native_height as f32);
|
||||
if nw <= 0.0 || nh <= 0.0 { return (self.native_width.max(1), self.native_height.max(1)); }
|
||||
let scale = (target_w as f32 / nw).min(target_h as f32 / nh).min(1.0);
|
||||
(((nw * scale) as u32).max(1), ((nh * scale) as u32).max(1))
|
||||
}
|
||||
|
||||
/// Get the output height (scaled dimensions)
|
||||
pub fn get_output_height(&self) -> u32 {
|
||||
self.output_height
|
||||
}
|
||||
|
||||
/// Decode a frame at the specified timestamp (public wrapper)
|
||||
/// Decode a frame at the specified timestamp, at native resolution (public wrapper).
|
||||
pub fn decode_frame(&mut self, timestamp: f64) -> Result<Vec<u8>, String> {
|
||||
self.get_frame(timestamp)
|
||||
// Software-only helper; request CPU output.
|
||||
match self.get_frame(timestamp, self.native_width, self.native_height, false)? {
|
||||
DecodedFrame::Cpu { rgba, .. } => Ok(rgba),
|
||||
DecodedFrame::Gpu(_) => Err("decode_frame: unexpected GPU frame".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Build an index of all keyframe positions in the video by scanning packets
|
||||
@@ -255,11 +471,21 @@ impl VideoDecoder {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get a decoded frame at the specified timestamp
|
||||
fn get_frame(&mut self, timestamp: f64) -> Result<Vec<u8>, String> {
|
||||
/// Decode the frame at `timestamp`, scaled to `capped_output(target_w, target_h)`. Returns GPU
|
||||
/// NV12 textures when hardware-decoding and `want_gpu` (the consumer is on the shared device,
|
||||
/// i.e. the preview); otherwise CPU RGBA. A hardware decoder serving a CPU consumer (export)
|
||||
/// downloads the surface via `av_hwframe_transfer_data` then swscales. The `VideoManager` caches
|
||||
/// the result, so the inner RGBA cache here is for CPU output only.
|
||||
fn get_frame(&mut self, timestamp: f64, target_w: u32, target_h: u32, want_gpu: bool) -> Result<DecodedFrame, String> {
|
||||
use std::time::Instant;
|
||||
let t_start = Instant::now();
|
||||
|
||||
// `hw` = decoder is opened in hardware mode (produces VAAPI surfaces).
|
||||
// `gpu_out` = return GPU textures (hw + the consumer can use them).
|
||||
let hw = self.hw_active();
|
||||
let gpu_out = hw && want_gpu;
|
||||
let (out_w, out_h) = self.capped_output(target_w, target_h);
|
||||
|
||||
// Round timestamp to nearest frame boundary to improve cache hits
|
||||
// This ensures that timestamps like 1.0001s and 0.9999s both map to frame 1.0s
|
||||
let frame_duration = 1.0 / self.fps;
|
||||
@@ -267,19 +493,41 @@ impl VideoDecoder {
|
||||
|
||||
// Convert timestamp to frame timestamp
|
||||
let frame_ts = (rounded_timestamp / self.time_base) as i64;
|
||||
let cache_key = (frame_ts, out_w, out_h);
|
||||
|
||||
// Check cache
|
||||
if let Some(cached_frame) = self.frame_cache.get(&frame_ts) {
|
||||
eprintln!("[Video Timing] Cache hit for ts={:.3}s ({}ms)", timestamp, t_start.elapsed().as_millis());
|
||||
return Ok(cached_frame.clone());
|
||||
// Check the inner RGBA cache (CPU output only; GPU frames are cached by VideoManager).
|
||||
if !gpu_out {
|
||||
if let Some(cached_frame) = self.frame_cache.get(&cache_key) {
|
||||
if video_debug() {
|
||||
eprintln!("[Video Timing] Cache hit for ts={:.3}s ({}ms)", timestamp, t_start.elapsed().as_millis());
|
||||
}
|
||||
return Ok(DecodedFrame::Cpu { rgba: cached_frame.clone(), width: out_w, height: out_h });
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if we need to seek
|
||||
// Seek if: no decoder open, going backwards, or jumping forward more than 2 seconds
|
||||
// Determine if we need to seek. Seek if: no decoder open, the *request* jumped backward
|
||||
// (scrub/step-back/loop), or the request is more than 2s ahead of the decoder's position.
|
||||
//
|
||||
// Detect "backward" from the request stream, NOT the decoded frame PTS. The requested
|
||||
// presentation time is rounded to a frame and converted through floats
|
||||
// (`round(ts/fd)*fd / time_base`), which routinely lands a frame *behind* the exact PTS of
|
||||
// the frame just produced — so `frame_ts < last_decoded_ts` falsely fires during smooth
|
||||
// forward playback (every ~10 frames → a 40ms seek + whole-GOP re-decode = the 4K jerk).
|
||||
// The request `frame_ts` is strictly monotonic while playing forward, so comparing against
|
||||
// the previous request never falses; a real backward scrub still decreases it.
|
||||
let need_seek = self.decoder.is_none()
|
||||
|| frame_ts < self.last_decoded_ts
|
||||
|| frame_ts < self.last_requested_ts
|
||||
|| frame_ts > self.last_decoded_ts + (2.0 / self.time_base) as i64;
|
||||
|
||||
if need_seek && video_debug() {
|
||||
let reason = if self.decoder.is_none() { "no decoder" }
|
||||
else if frame_ts < self.last_requested_ts { "backward" }
|
||||
else { "forward>2s" };
|
||||
eprintln!("[Video Seek?] need_seek={reason} frame_ts={frame_ts} last_requested_ts={} last_decoded_ts={}",
|
||||
self.last_requested_ts, self.last_decoded_ts);
|
||||
}
|
||||
self.last_requested_ts = frame_ts;
|
||||
|
||||
if need_seek {
|
||||
let t_seek_start = Instant::now();
|
||||
|
||||
@@ -292,8 +540,10 @@ impl VideoDecoder {
|
||||
let keyframe_seconds = keyframe_ts_stream as f64 * self.time_base;
|
||||
let keyframe_ts_av = (keyframe_seconds * 1_000_000.0) as i64; // AV_TIME_BASE = 1000000
|
||||
|
||||
eprintln!("[Video Seek] Target: {} | Keyframe(stream): {} | Keyframe(AV): {} | Index size: {}",
|
||||
frame_ts, keyframe_ts_stream, keyframe_ts_av, self.keyframe_positions.len());
|
||||
if video_debug() {
|
||||
eprintln!("[Video Seek] Target: {} | Keyframe(stream): {} | Keyframe(AV): {} | Index size: {}",
|
||||
frame_ts, keyframe_ts_stream, keyframe_ts_av, self.keyframe_positions.len());
|
||||
}
|
||||
|
||||
// Reopen input (a fresh BlobReader for packed sources).
|
||||
let mut owned = self.source.open()
|
||||
@@ -306,15 +556,37 @@ impl VideoDecoder {
|
||||
input.seek(keyframe_ts_av, keyframe_ts_av..(keyframe_ts_av + 1))
|
||||
.map_err(|e| format!("Seek failed: {}", e))?;
|
||||
|
||||
eprintln!("[Video Timing] Seek call took {}ms", t_seek_start.elapsed().as_millis());
|
||||
if video_debug() {
|
||||
eprintln!("[Video Timing] Seek call took {}ms", t_seek_start.elapsed().as_millis());
|
||||
}
|
||||
|
||||
let context_decoder = ffmpeg::codec::context::Context::from_parameters(
|
||||
input.streams().best(ffmpeg::media::Type::Video).unwrap().parameters()
|
||||
).map_err(|e| e.to_string())?;
|
||||
|
||||
let decoder = context_decoder.decoder().video()
|
||||
.map_err(|e| e.to_string())?;
|
||||
self.decoder = Some(decoder);
|
||||
let mut dec_ctx = context_decoder.decoder();
|
||||
if hw {
|
||||
// Attach the VAAPI device + format selector before opening so the decoder
|
||||
// produces hardware surfaces.
|
||||
unsafe {
|
||||
let ctx = dec_ctx.as_mut_ptr();
|
||||
let hwdev = self.hw_device.unwrap().0 as *mut ffmpeg::ffi::AVBufferRef;
|
||||
(*ctx).hw_device_ctx = ffmpeg::ffi::av_buffer_ref(hwdev);
|
||||
(*ctx).get_format = Some(get_vaapi_format);
|
||||
}
|
||||
}
|
||||
match dec_ctx.video() {
|
||||
Ok(decoder) => self.decoder = Some(decoder),
|
||||
Err(e) if hw => {
|
||||
// Hardware decode unavailable for this clip — fall back to software. This
|
||||
// frame fails; the next call rebuilds a software decoder.
|
||||
eprintln!("[Video] hardware decode unavailable ({e}); falling back to software");
|
||||
self.hw_failed = true;
|
||||
self.decoder = None;
|
||||
return Err(format!("hw decode init failed: {e}"));
|
||||
}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
self.input = Some(owned);
|
||||
// Set last_decoded_ts to just before the seek target so forward playback works
|
||||
@@ -327,82 +599,87 @@ impl VideoDecoder {
|
||||
|
||||
// Decode frames until we find the one closest to our target timestamp
|
||||
let mut best_frame_data: Option<Vec<u8>> = None;
|
||||
let mut best_gpu: Option<GpuVideoFrame> = None;
|
||||
let mut best_frame_ts: Option<i64> = None;
|
||||
let t_decode_start = Instant::now();
|
||||
let mut decode_count = 0;
|
||||
let mut scale_time_ms = 0u128;
|
||||
let mut hw_import_failed = false;
|
||||
|
||||
for (stream, packet) in input.packets() {
|
||||
if stream.index() == self.stream_index {
|
||||
decoder.send_packet(&packet)
|
||||
.map_err(|e| e.to_string())?;
|
||||
'decode: {
|
||||
for (stream, packet) in input.packets() {
|
||||
if stream.index() == self.stream_index {
|
||||
decoder.send_packet(&packet)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let mut frame = ffmpeg::util::frame::Video::empty();
|
||||
while decoder.receive_frame(&mut frame).is_ok() {
|
||||
decode_count += 1;
|
||||
let current_frame_ts = frame.timestamp().unwrap_or(0);
|
||||
self.last_decoded_ts = current_frame_ts; // Update last decoded position
|
||||
|
||||
// Check if this frame is closer to our target than the previous best
|
||||
let is_better = match best_frame_ts {
|
||||
None => true,
|
||||
Some(best_ts) => {
|
||||
(current_frame_ts - frame_ts).abs() < (best_ts - frame_ts).abs()
|
||||
let mut frame = ffmpeg::util::frame::Video::empty();
|
||||
while decoder.receive_frame(&mut frame).is_ok() {
|
||||
decode_count += 1;
|
||||
match process_decoded_video_frame(
|
||||
&mut frame, decoder, gpu_out, hw, out_w, out_h, frame_ts,
|
||||
self.importer.as_ref(), &mut self.scaler,
|
||||
&mut best_frame_data, &mut best_gpu, &mut best_frame_ts,
|
||||
&mut self.last_decoded_ts, &mut scale_time_ms,
|
||||
)? {
|
||||
FrameOutcome::Continue => {}
|
||||
FrameOutcome::ReachedTarget => break 'decode,
|
||||
FrameOutcome::HwImportFailed => {
|
||||
self.hw_failed = true;
|
||||
hw_import_failed = true;
|
||||
break 'decode;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if is_better {
|
||||
let t_scale_start = Instant::now();
|
||||
|
||||
// Convert to RGBA and scale to output size
|
||||
let mut scaler = ffmpeg::software::scaling::context::Context::get(
|
||||
frame.format(),
|
||||
frame.width(),
|
||||
frame.height(),
|
||||
ffmpeg::format::Pixel::RGBA,
|
||||
self.output_width,
|
||||
self.output_height,
|
||||
ffmpeg::software::scaling::flag::Flags::BILINEAR,
|
||||
).map_err(|e| e.to_string())?;
|
||||
|
||||
let mut rgb_frame = ffmpeg::util::frame::Video::empty();
|
||||
scaler.run(&frame, &mut rgb_frame)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
// Remove stride padding to create tightly packed RGBA data
|
||||
let width = self.output_width as usize;
|
||||
let height = self.output_height as usize;
|
||||
let stride = rgb_frame.stride(0);
|
||||
let row_size = width * 4; // RGBA = 4 bytes per pixel
|
||||
let source_data = rgb_frame.data(0);
|
||||
|
||||
let mut packed_data = Vec::with_capacity(row_size * height);
|
||||
for y in 0..height {
|
||||
let row_start = y * stride;
|
||||
let row_end = row_start + row_size;
|
||||
packed_data.extend_from_slice(&source_data[row_start..row_end]);
|
||||
}
|
||||
|
||||
scale_time_ms += t_scale_start.elapsed().as_millis();
|
||||
best_frame_data = Some(packed_data);
|
||||
best_frame_ts = Some(current_frame_ts);
|
||||
}
|
||||
|
||||
// If we've reached or passed the target timestamp, we can stop
|
||||
if current_frame_ts >= frame_ts {
|
||||
// Found our frame, cache and return it
|
||||
if let Some(data) = best_frame_data {
|
||||
let total_time = t_start.elapsed().as_millis();
|
||||
let decode_time = t_decode_start.elapsed().as_millis();
|
||||
eprintln!("[Video Timing] ts={:.3}s | Decoded {} frames in {}ms | Scale: {}ms | Total: {}ms",
|
||||
timestamp, decode_count, decode_time, scale_time_ms, total_time);
|
||||
self.frame_cache.put(frame_ts, data.clone());
|
||||
return Ok(data);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush: the codec may still hold buffered frames (B-frame reorder delay) past the
|
||||
// last packet. Drain them so requesting the final frame(s) of a clip — scrubbing to
|
||||
// the end or exporting the tail — doesn't fail with "Failed to decode frame".
|
||||
if !hw_import_failed {
|
||||
let _ = decoder.send_eof();
|
||||
let mut frame = ffmpeg::util::frame::Video::empty();
|
||||
while decoder.receive_frame(&mut frame).is_ok() {
|
||||
decode_count += 1;
|
||||
match process_decoded_video_frame(
|
||||
&mut frame, decoder, gpu_out, hw, out_w, out_h, frame_ts,
|
||||
self.importer.as_ref(), &mut self.scaler,
|
||||
&mut best_frame_data, &mut best_gpu, &mut best_frame_ts,
|
||||
&mut self.last_decoded_ts, &mut scale_time_ms,
|
||||
)? {
|
||||
FrameOutcome::Continue => {}
|
||||
FrameOutcome::ReachedTarget => break 'decode,
|
||||
FrameOutcome::HwImportFailed => {
|
||||
self.hw_failed = true;
|
||||
hw_import_failed = true;
|
||||
break 'decode;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if video_debug() {
|
||||
let total_time = t_start.elapsed().as_millis();
|
||||
let decode_time = t_decode_start.elapsed().as_millis();
|
||||
eprintln!("[Video Timing] ts={:.3}s | Decoded {} frames in {}ms | Scale: {}ms | Total: {}ms | {}",
|
||||
timestamp, decode_count, decode_time, scale_time_ms, total_time, if hw { "hw" } else { "sw" });
|
||||
}
|
||||
|
||||
// Reached the target, EOF, or HW import failed mid-stream.
|
||||
if hw_import_failed {
|
||||
self.decoder = None; // force a software rebuild next call (decoder borrow ended here)
|
||||
self.input = None;
|
||||
return Err("hardware frame import failed; retrying software".to_string());
|
||||
}
|
||||
// Return the closest frame we found, if any.
|
||||
if gpu_out {
|
||||
if let Some(gpu) = best_gpu.take() {
|
||||
return Ok(DecodedFrame::Gpu(gpu));
|
||||
}
|
||||
} else if let Some(data) = best_frame_data {
|
||||
self.frame_cache.put(cache_key, data.clone());
|
||||
return Ok(DecodedFrame::Cpu { rgba: data, width: out_w, height: out_h });
|
||||
}
|
||||
|
||||
eprintln!("[Video Decoder] ERROR: Failed to decode frame for timestamp {}", timestamp);
|
||||
@@ -455,8 +732,25 @@ pub fn generate_keyframe_thumbnails(
|
||||
if should_skip(ks) {
|
||||
continue;
|
||||
}
|
||||
if let Ok(rgba) = decoder.get_frame(ks) {
|
||||
on_thumb(ks, Arc::new(rgba));
|
||||
// Decode at the thumbnail width (large height so width is the constraint), capped to native.
|
||||
// Thumbnail decoders are always software (no hardware importer).
|
||||
if let Ok(DecodedFrame::Cpu { rgba, width, height }) = decoder.get_frame(ks, thumb_width, 100_000, false) {
|
||||
// `capped_output` never upscales, so a source narrower than `thumb_width` decodes
|
||||
// smaller — but `get_thumbnail_at` reconstructs height assuming an exact `thumb_width`.
|
||||
// Force the exact width here (rare path) so that assumption holds and the thumbnail
|
||||
// isn't shown stretched.
|
||||
let data = if width == thumb_width || width == 0 || height == 0 {
|
||||
rgba
|
||||
} else {
|
||||
let new_h = ((thumb_width as u64 * height as u64) / width as u64).max(1) as u32;
|
||||
match image::RgbaImage::from_raw(width, height, rgba) {
|
||||
Some(img) => image::imageops::resize(
|
||||
&img, thumb_width, new_h, image::imageops::FilterType::Triangle,
|
||||
).into_raw(),
|
||||
None => continue,
|
||||
}
|
||||
};
|
||||
on_thumb(ks, Arc::new(data));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -520,10 +814,98 @@ pub fn probe_video(source: &VideoSource) -> Result<VideoMetadata, String> {
|
||||
pub struct VideoFrame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// CPU-decoded sRGB RGBA8 (software path). Empty when `gpu` is `Some`.
|
||||
pub rgba_data: Arc<Vec<u8>>,
|
||||
/// Hardware-decoded frame living on the GPU (NV12 plane textures). When `Some`, the compositor
|
||||
/// samples it directly and `rgba_data` is empty.
|
||||
pub gpu: Option<GpuVideoFrame>,
|
||||
pub timestamp: f64,
|
||||
}
|
||||
|
||||
/// A hardware-decoded video frame on the GPU: two NV12 plane textures (Y = R8, UV = RG8) imported
|
||||
/// from a VAAPI DMA-BUF on the editor's shared wgpu device. The compositor samples these directly
|
||||
/// (NV12→RGB), no CPU copy.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GpuVideoFrame {
|
||||
pub y: Arc<wgpu::Texture>,
|
||||
pub uv: Arc<wgpu::Texture>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Source YUV range: true = full/PC (0–255), false = limited/TV (16–235). Drives the NV12→RGB
|
||||
/// offset/scale in the compositor.
|
||||
pub full_range: bool,
|
||||
/// Y'CbCr→R'G'B' matrix coefficients derived from the frame's colorspace (BT.709/601/2020),
|
||||
/// so SD (BT.601) and HD/UHD clips each convert correctly: `[Cr→R, Cb→G, Cr→G, Cb→B]`.
|
||||
/// R = Y + c[0]·Cr, G = Y + c[1]·Cb + c[2]·Cr, B = Y + c[3]·Cb
|
||||
pub coeffs: [f32; 4],
|
||||
/// Opto-electronic transfer of the encoded R'G'B' — the compositor applies the matching EOTF to
|
||||
/// reach scene-linear (graphics white = 1.0). HDR (PQ/HLG) values exceed 1.0.
|
||||
pub transfer: VideoTransfer,
|
||||
/// Colour primaries; BT.2020 is gamut-mapped to the compositor's BT.709 space in linear light.
|
||||
pub primaries: VideoPrimaries,
|
||||
}
|
||||
|
||||
/// Transfer characteristic of a decoded video frame (selects the EOTF in the NV12→linear pass).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VideoTransfer {
|
||||
/// SDR gamma (BT.709/sRGB/601/gamma22) — approximated by the sRGB EOTF.
|
||||
Gamma,
|
||||
/// SMPTE ST 2084 (PQ) — absolute, normalized so 203 nits (graphics white) = 1.0.
|
||||
Pq,
|
||||
/// ARIB STD-B67 (HLG) — scene-referred, normalized so reference white ≈ 1.0.
|
||||
Hlg,
|
||||
}
|
||||
|
||||
/// Colour primaries of a decoded video frame.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum VideoPrimaries {
|
||||
/// BT.709 / sRGB (also used for BT.601, whose primaries differ only slightly).
|
||||
Bt709,
|
||||
/// BT.2020 (wide gamut) — converted to BT.709 in linear light by the compositor.
|
||||
Bt2020,
|
||||
}
|
||||
|
||||
/// Y'CbCr→R'G'B' matrix coefficients (`[Cr→R, Cb→G, Cr→G, Cb→B]`) from the luma weights `kr`/`kb`
|
||||
/// (`kg = 1−kr−kb`). BT.709 → `[1.5748, −0.1873, −0.4681, 1.8556]`.
|
||||
pub fn ycbcr_coeffs(kr: f32, kb: f32) -> [f32; 4] {
|
||||
let kg = 1.0 - kr - kb;
|
||||
[
|
||||
2.0 * (1.0 - kr),
|
||||
-2.0 * kb * (1.0 - kb) / kg,
|
||||
-2.0 * kr * (1.0 - kr) / kg,
|
||||
2.0 * (1.0 - kb),
|
||||
]
|
||||
}
|
||||
|
||||
/// Imports a decoded VAAPI surface (a `*mut AVFrame`, passed as an opaque pointer so core needn't
|
||||
/// reference the GPU crate's ffmpeg-sys types) into [`GpuVideoFrame`] textures on the shared device.
|
||||
/// Implemented by the editor; `gpu-video-encoder` does the actual DMA-BUF import.
|
||||
pub trait HwVideoImporter: Send + Sync {
|
||||
/// # Safety
|
||||
/// `av_frame` must be a valid `*mut ffmpeg_sys_next::AVFrame` holding a VAAPI surface.
|
||||
unsafe fn import(&self, av_frame: *mut std::ffi::c_void) -> Option<GpuVideoFrame>;
|
||||
}
|
||||
|
||||
/// Opaque handle to the FFmpeg VAAPI hardware device (`*mut AVBufferRef`), created by the editor and
|
||||
/// handed to core so decoders can attach it as `hw_device_ctx`. Core never frees it (the editor owns
|
||||
/// it for the app's lifetime).
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct HwDeviceHandle(pub *mut std::ffi::c_void);
|
||||
// SAFETY: the pointer is an AVBufferRef whose refcount is managed by FFmpeg; we only `av_buffer_ref`
|
||||
// it (atomic) and never free it, so sharing the handle across threads is sound.
|
||||
unsafe impl Send for HwDeviceHandle {}
|
||||
unsafe impl Sync for HwDeviceHandle {}
|
||||
|
||||
/// Approximate resident bytes of a cached frame for the byte budget: the CPU RGBA buffer, or for a
|
||||
/// GPU (NV12) frame ~`w*h*3/2` of VRAM, so GPU frames stay bounded too.
|
||||
fn frame_cache_bytes(frame: &VideoFrame) -> usize {
|
||||
if frame.gpu.is_some() {
|
||||
(frame.width as usize * frame.height as usize * 3) / 2
|
||||
} else {
|
||||
frame.rgba_data.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Manages video decoders and frame caching for multiple video clips
|
||||
pub struct VideoManager {
|
||||
/// Pool of video decoders, one per clip
|
||||
@@ -533,7 +915,7 @@ pub struct VideoManager {
|
||||
/// zero-copy rendering. Bounded by a **byte budget** (not a frame count, which
|
||||
/// would be unsafe across resolutions — a 4K frame is ~33MB vs ~2MB at 800x600)
|
||||
/// so playback of arbitrarily long video never grows unbounded.
|
||||
frame_cache: LruCache<(Uuid, i64), Arc<VideoFrame>>,
|
||||
frame_cache: LruCache<(Uuid, i64, u32, u32, bool), Arc<VideoFrame>>,
|
||||
/// Running total of bytes held in `frame_cache` (sum of each frame's RGBA len),
|
||||
/// kept in sync on insert/evict/remove so eviction is O(1) per frame.
|
||||
frame_cache_bytes: usize,
|
||||
@@ -549,6 +931,15 @@ pub struct VideoManager {
|
||||
|
||||
/// Maximum number of frames to cache per decoder
|
||||
cache_size: usize,
|
||||
|
||||
/// Hardware (VAAPI) decode, injected by the editor once the shared device is up. When set, each
|
||||
/// decoder attaches the VAAPI device and imports frames as GPU textures via `hw_importer`.
|
||||
hw_device: Option<HwDeviceHandle>,
|
||||
hw_importer: Option<Arc<dyn HwVideoImporter>>,
|
||||
/// Whether the current render pass can consume GPU textures (preview = true; export = false,
|
||||
/// since it composites on a different device → a hardware decoder downloads to CPU instead).
|
||||
/// Set by the render caller before each pass.
|
||||
render_hardware_ok: bool,
|
||||
}
|
||||
|
||||
/// Byte budget for [`VideoManager::frame_cache`] (decoded full-resolution frames).
|
||||
@@ -571,9 +962,34 @@ impl VideoManager {
|
||||
thumbnail_cache: HashMap::new(),
|
||||
thumbnails_complete: std::collections::HashSet::new(),
|
||||
cache_size,
|
||||
hw_device: None,
|
||||
hw_importer: None,
|
||||
render_hardware_ok: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set whether the upcoming render pass can consume GPU video textures (preview = true; export =
|
||||
/// false). Call before `render_document_for_compositing`.
|
||||
pub fn set_render_hardware_ok(&mut self, ok: bool) {
|
||||
self.render_hardware_ok = ok;
|
||||
}
|
||||
|
||||
/// Enable hardware (VAAPI) decode for all clips. Injected by the editor once the shared wgpu
|
||||
/// device is active; `hw_device` is the FFmpeg VAAPI device and `importer` imports decoded
|
||||
/// surfaces as GPU textures on that device. Applies to existing and future decoders. Clears the
|
||||
/// frame cache (cached CPU frames would otherwise hide the new GPU frames).
|
||||
pub fn set_hardware_decode(&mut self, hw_device: HwDeviceHandle, importer: Arc<dyn HwVideoImporter>) {
|
||||
self.hw_device = Some(hw_device);
|
||||
self.hw_importer = Some(Arc::clone(&importer));
|
||||
for dec in self.decoders.values() {
|
||||
if let Ok(mut d) = dec.lock() {
|
||||
d.set_hardware(hw_device, Arc::clone(&importer));
|
||||
}
|
||||
}
|
||||
self.frame_cache.clear();
|
||||
self.frame_cache_bytes = 0;
|
||||
}
|
||||
|
||||
/// Load a video file and create a decoder for it
|
||||
///
|
||||
/// `target_width` and `target_height` specify the maximum dimensions
|
||||
@@ -593,7 +1009,7 @@ impl VideoManager {
|
||||
let metadata = probe_video(&source)?;
|
||||
|
||||
// Create decoder with target dimensions, without building keyframe index
|
||||
let decoder = VideoDecoder::new(
|
||||
let mut decoder = VideoDecoder::new(
|
||||
source,
|
||||
self.cache_size,
|
||||
Some(target_width),
|
||||
@@ -601,6 +1017,11 @@ impl VideoManager {
|
||||
false, // Don't build keyframe index synchronously
|
||||
)?;
|
||||
|
||||
// Inherit hardware decode if the manager has it configured.
|
||||
if let (Some(hw), Some(imp)) = (self.hw_device, &self.hw_importer) {
|
||||
decoder.set_hardware(hw, Arc::clone(imp));
|
||||
}
|
||||
|
||||
// Store decoder in pool
|
||||
self.decoders.insert(clip_id, Arc::new(Mutex::new(decoder)));
|
||||
|
||||
@@ -609,35 +1030,67 @@ impl VideoManager {
|
||||
|
||||
/// Get a decoded frame for a specific clip at a specific timestamp
|
||||
///
|
||||
/// Returns None if the clip is not loaded or decoding fails.
|
||||
/// Frames are cached for performance.
|
||||
pub fn get_frame(&mut self, clip_id: &Uuid, timestamp: f64) -> Option<Arc<VideoFrame>> {
|
||||
// Convert timestamp to milliseconds for cache key
|
||||
let timestamp_ms = (timestamp * 1000.0) as i64;
|
||||
let cache_key = (*clip_id, timestamp_ms);
|
||||
/// Returns None if the clip is not loaded or decoding fails. Frames are cached.
|
||||
/// Whether a hardware decoder returns a GPU texture or downloads to CPU RGBA depends on
|
||||
/// [`set_render_hardware_ok`](Self::set_render_hardware_ok), set per render pass (true for the
|
||||
/// preview, false for export, which composites on a different device).
|
||||
pub fn get_frame(&mut self, clip_id: &Uuid, timestamp: f64, target_w: u32, target_h: u32) -> Option<Arc<VideoFrame>> {
|
||||
// Whether this pass wants (and can produce) a GPU frame. Gated on HW being configured at all
|
||||
// so that with software-only decode preview and export share one cache entry (no double-cache).
|
||||
let want_gpu = self.render_hardware_ok && self.hw_device.is_some();
|
||||
self.get_frame_inner(clip_id, timestamp, target_w, target_h, want_gpu)
|
||||
}
|
||||
|
||||
/// Like [`get_frame`](Self::get_frame) but always returns a CPU (RGBA) frame, ignoring the
|
||||
/// render-pass hardware flag. For consumers that need pixel bytes (thumbnails, image readback)
|
||||
/// regardless of whether a render pass last enabled GPU frames.
|
||||
pub fn get_frame_cpu(&mut self, clip_id: &Uuid, timestamp: f64, target_w: u32, target_h: u32) -> Option<Arc<VideoFrame>> {
|
||||
self.get_frame_inner(clip_id, timestamp, target_w, target_h, false)
|
||||
}
|
||||
|
||||
fn get_frame_inner(&mut self, clip_id: &Uuid, timestamp: f64, target_w: u32, target_h: u32, want_gpu: bool) -> Option<Arc<VideoFrame>> {
|
||||
// Get the decoder for this clip. Clone the Arc so we don't hold a borrow of
|
||||
// `self.decoders` across the `&mut self` cache insert below.
|
||||
let decoder_arc = Arc::clone(self.decoders.get(clip_id)?);
|
||||
|
||||
// Key the cache on the video FRAME INDEX, not milliseconds. A UI that refreshes finer than
|
||||
// the video frame rate (e.g. a 60 Hz canvas on a 30 fps clip) would otherwise miss the cache
|
||||
// on every sub-frame request and decode the NEXT frame each time — advancing the video faster
|
||||
// than the clock (it plays sped-up). Rounding to round(ts·fps) maps all requests within one
|
||||
// frame to a single entry, so each frame is decoded exactly once.
|
||||
let fps = decoder_arc.lock().ok()?.fps;
|
||||
let frame_index = if fps > 0.0 { (timestamp * fps).round() as i64 } else { (timestamp * 1000.0) as i64 };
|
||||
// The key also includes (target size, want_gpu): preview (GPU, preview res) and export
|
||||
// (CPU, export res) request the same clip/time and must not collide or cross representation.
|
||||
let cache_key = (*clip_id, frame_index, target_w, target_h, want_gpu);
|
||||
|
||||
// Check frame cache first
|
||||
if let Some(cached_frame) = self.frame_cache.get(&cache_key) {
|
||||
return Some(Arc::clone(cached_frame));
|
||||
}
|
||||
|
||||
// Get decoder for this clip. Clone the Arc so we don't hold a borrow of
|
||||
// `self.decoders` across the `&mut self` cache insert below.
|
||||
let decoder_arc = Arc::clone(self.decoders.get(clip_id)?);
|
||||
let mut decoder = decoder_arc.lock().ok()?;
|
||||
|
||||
// Decode the frame
|
||||
let rgba_data = decoder.get_frame(timestamp).ok()?;
|
||||
let width = decoder.output_width;
|
||||
let height = decoder.output_height;
|
||||
// Decode the frame at the requested target (capped to native by the decoder).
|
||||
let decoded = decoder.get_frame(timestamp, target_w, target_h, want_gpu).ok()?;
|
||||
drop(decoder); // release the lock before touching `self`
|
||||
|
||||
// Create VideoFrame and cache it
|
||||
let frame = Arc::new(VideoFrame {
|
||||
width,
|
||||
height,
|
||||
rgba_data: Arc::new(rgba_data),
|
||||
timestamp,
|
||||
// Create VideoFrame and cache it.
|
||||
let frame = Arc::new(match decoded {
|
||||
DecodedFrame::Cpu { rgba, width, height } => VideoFrame {
|
||||
width,
|
||||
height,
|
||||
rgba_data: Arc::new(rgba),
|
||||
gpu: None,
|
||||
timestamp,
|
||||
},
|
||||
DecodedFrame::Gpu(gpu) => VideoFrame {
|
||||
width: gpu.width,
|
||||
height: gpu.height,
|
||||
rgba_data: Arc::new(Vec::new()),
|
||||
gpu: Some(gpu),
|
||||
timestamp,
|
||||
},
|
||||
});
|
||||
|
||||
self.cache_frame(cache_key, Arc::clone(&frame));
|
||||
@@ -647,16 +1100,16 @@ impl VideoManager {
|
||||
|
||||
/// Insert a frame into the byte-budgeted cache, evicting least-recently-used
|
||||
/// frames until the total is within [`FRAME_CACHE_BYTE_BUDGET`].
|
||||
fn cache_frame(&mut self, key: (Uuid, i64), frame: Arc<VideoFrame>) {
|
||||
let bytes = frame.rgba_data.len();
|
||||
fn cache_frame(&mut self, key: (Uuid, i64, u32, u32, bool), frame: Arc<VideoFrame>) {
|
||||
let bytes = frame_cache_bytes(&frame);
|
||||
if let Some(old) = self.frame_cache.put(key, frame) {
|
||||
self.frame_cache_bytes = self.frame_cache_bytes.saturating_sub(old.rgba_data.len());
|
||||
self.frame_cache_bytes = self.frame_cache_bytes.saturating_sub(frame_cache_bytes(&old));
|
||||
}
|
||||
self.frame_cache_bytes += bytes;
|
||||
// Keep at least one frame resident even if it alone exceeds the budget.
|
||||
while self.frame_cache_bytes > FRAME_CACHE_BYTE_BUDGET && self.frame_cache.len() > 1 {
|
||||
if let Some((_, evicted)) = self.frame_cache.pop_lru() {
|
||||
self.frame_cache_bytes = self.frame_cache_bytes.saturating_sub(evicted.rgba_data.len());
|
||||
self.frame_cache_bytes = self.frame_cache_bytes.saturating_sub(frame_cache_bytes(&evicted));
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
@@ -763,15 +1216,15 @@ impl VideoManager {
|
||||
|
||||
// Remove all cached frames for this clip (LruCache has no retain; collect
|
||||
// matching keys, then pop each, keeping the byte total in sync).
|
||||
let keys: Vec<(Uuid, i64)> = self
|
||||
let keys: Vec<(Uuid, i64, u32, u32, bool)> = self
|
||||
.frame_cache
|
||||
.iter()
|
||||
.filter(|((id, _), _)| id == clip_id)
|
||||
.filter(|((id, _, _, _, _), _)| id == clip_id)
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in keys {
|
||||
if let Some(frame) = self.frame_cache.pop(&key) {
|
||||
self.frame_cache_bytes = self.frame_cache_bytes.saturating_sub(frame.rgba_data.len());
|
||||
self.frame_cache_bytes = self.frame_cache_bytes.saturating_sub(frame_cache_bytes(&frame));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lightningbeam-editor"
|
||||
version = "1.0.6-alpha"
|
||||
version = "1.0.7-alpha"
|
||||
edition = "2021"
|
||||
description = "Multimedia editor for audio, video and 2D animation"
|
||||
license = "GPL-3.0-or-later"
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
---
|
||||
|
||||
The following Lucide icons are derived from the Feather project:
|
||||
|
||||
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
|
||||
|
||||
The MIT License (MIT) (for the icons listed above)
|
||||
|
||||
Copyright (c) 2013-present Cole Bemis
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Binary file not shown.
@@ -99,6 +99,14 @@
|
||||
--font-size-small: 11px;
|
||||
--font-size-default: 13px;
|
||||
--pane-border-width: 1px;
|
||||
|
||||
/* Modal backdrop (translucent) + intent/category accents (shared by light & dark) */
|
||||
--scrim: #10141ab0;
|
||||
--accent-coral: #e8826b;
|
||||
--accent-cyan: #54c3e8;
|
||||
--accent-amber: #f4a340;
|
||||
--accent-pink: #c75b8a;
|
||||
--accent-violet: #8a6ec0;
|
||||
}
|
||||
|
||||
/* ============================================
|
||||
|
||||
@@ -26,9 +26,9 @@ impl CpuYuvConverter {
|
||||
/// # Arguments
|
||||
/// * `width` - Frame width in pixels
|
||||
/// * `height` - Frame height in pixels
|
||||
pub fn new(width: u32, height: u32) -> Result<Self, String> {
|
||||
pub fn new(width: u32, height: u32, full_range: bool) -> Result<Self, String> {
|
||||
// BT.709 (HD) RGBA→YUV420p context, created once.
|
||||
let scaler = ffmpeg::software::scaling::Context::get(
|
||||
let mut scaler = ffmpeg::software::scaling::Context::get(
|
||||
ffmpeg::format::Pixel::RGBA,
|
||||
width,
|
||||
height,
|
||||
@@ -38,6 +38,23 @@ impl CpuYuvConverter {
|
||||
ffmpeg::software::scaling::Flags::BILINEAR,
|
||||
)
|
||||
.map_err(|e| format!("Failed to create swscale context: {}", e))?;
|
||||
|
||||
// swscale defaults to BT.601 + limited range; force BT.709 with the requested output
|
||||
// range so this fallback matches the GPU path and the encoder's color tags
|
||||
// (otherwise non-%8-width exports come out with shifted hue / wrong levels). There is
|
||||
// no safe ffmpeg-next wrapper for sws_setColorspaceDetails, so this is the raw call.
|
||||
unsafe {
|
||||
let coeffs = ffmpeg::ffi::sws_getCoefficients(ffmpeg::ffi::SWS_CS_ITU709 as i32);
|
||||
let dst_range = if full_range { 1 } else { 0 };
|
||||
let one = 1 << 16; // 16.16 fixed-point 1.0
|
||||
ffmpeg::ffi::sws_setColorspaceDetails(
|
||||
scaler.as_mut_ptr(),
|
||||
coeffs, 1, // source table (RGB input is full-range)
|
||||
coeffs, dst_range, // dest table = BT.709, dest range = requested
|
||||
0, one, one, // brightness, contrast, saturation (neutral)
|
||||
);
|
||||
}
|
||||
|
||||
let rgba_frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, width, height);
|
||||
let yuv_frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::YUV420P, width, height);
|
||||
Ok(Self { width, height, scaler, rgba_frame, yuv_frame })
|
||||
@@ -90,13 +107,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_converter_creation() {
|
||||
let converter = CpuYuvConverter::new(1920, 1080);
|
||||
let converter = CpuYuvConverter::new(1920, 1080, true);
|
||||
assert!(converter.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_conversion_output_sizes() {
|
||||
let mut converter = CpuYuvConverter::new(1920, 1080).unwrap();
|
||||
let mut converter = CpuYuvConverter::new(1920, 1080, true).unwrap();
|
||||
|
||||
// Create dummy RGBA data (all black)
|
||||
let rgba_data = vec![0u8; 1920 * 1080 * 4];
|
||||
@@ -117,7 +134,7 @@ mod tests {
|
||||
#[test]
|
||||
#[should_panic(expected = "RGBA data size mismatch")]
|
||||
fn test_wrong_input_size_panics() {
|
||||
let mut converter = CpuYuvConverter::new(1920, 1080).unwrap();
|
||||
let mut converter = CpuYuvConverter::new(1920, 1080, true).unwrap();
|
||||
|
||||
// Wrong size input
|
||||
let rgba_data = vec![0u8; 1000];
|
||||
|
||||
@@ -6,7 +6,7 @@ use eframe::egui;
|
||||
use lightningbeam_core::export::{
|
||||
AudioExportSettings, AudioFormat,
|
||||
ImageExportSettings, ImageFormat,
|
||||
VideoExportSettings, VideoCodec, VideoQuality,
|
||||
VideoExportSettings, VideoCodec, VideoQuality, ColorRange,
|
||||
};
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -25,6 +25,8 @@ pub enum ExportType {
|
||||
Audio,
|
||||
Image,
|
||||
Video,
|
||||
/// Vector-only SVG of the current frame (lossless; raster/video layers skipped).
|
||||
Svg,
|
||||
}
|
||||
|
||||
/// Export result from dialog
|
||||
@@ -34,6 +36,8 @@ pub enum ExportResult {
|
||||
Image(ImageExportSettings, PathBuf),
|
||||
VideoOnly(VideoExportSettings, PathBuf),
|
||||
VideoWithAudio(VideoExportSettings, AudioExportSettings, PathBuf),
|
||||
/// SVG of vector layers at the given document time.
|
||||
Svg(f64, PathBuf),
|
||||
}
|
||||
|
||||
/// Export dialog state
|
||||
@@ -156,6 +160,7 @@ impl ExportDialog {
|
||||
ExportType::Audio => self.audio_settings.format.extension(),
|
||||
ExportType::Image => self.image_settings.format.extension(),
|
||||
ExportType::Video => self.video_settings.codec.container_format(),
|
||||
ExportType::Svg => "svg",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,11 +203,12 @@ impl ExportDialog {
|
||||
ExportType::Audio => "Export Audio",
|
||||
ExportType::Image => "Export Image",
|
||||
ExportType::Video => "Export Video",
|
||||
ExportType::Svg => "Export SVG",
|
||||
};
|
||||
|
||||
let modal_response = egui::Modal::new(egui::Id::new("export_dialog_modal"))
|
||||
.show(ctx, |ui| {
|
||||
ui.set_width(500.0);
|
||||
ui.set_width(crate::mobile::dialog_width(ctx, 500.0));
|
||||
|
||||
ui.heading(window_title);
|
||||
ui.add_space(8.0);
|
||||
@@ -219,6 +225,7 @@ impl ExportDialog {
|
||||
(ExportType::Audio, "Audio"),
|
||||
(ExportType::Image, "Image"),
|
||||
(ExportType::Video, "Video"),
|
||||
(ExportType::Svg, "SVG"),
|
||||
] {
|
||||
if ui.selectable_value(&mut self.export_type, variant, label).clicked() {
|
||||
self.update_filename_extension();
|
||||
@@ -235,6 +242,7 @@ impl ExportDialog {
|
||||
ExportType::Audio => self.render_audio_basic(ui),
|
||||
ExportType::Image => self.render_image_settings(ui),
|
||||
ExportType::Video => self.render_video_basic(ui),
|
||||
ExportType::Svg => self.render_svg_settings(ui),
|
||||
}
|
||||
|
||||
ui.add_space(12.0);
|
||||
@@ -253,6 +261,7 @@ impl ExportDialog {
|
||||
ExportType::Audio => self.render_audio_advanced(ui),
|
||||
ExportType::Image => self.render_image_advanced(ui),
|
||||
ExportType::Video => self.render_video_advanced(ui),
|
||||
ExportType::Svg => {} // SVG has no advanced settings
|
||||
}
|
||||
}
|
||||
|
||||
@@ -356,6 +365,20 @@ impl ExportDialog {
|
||||
}
|
||||
}
|
||||
|
||||
/// Render SVG export settings — just the frame time (reuses the image time field).
|
||||
fn render_svg_settings(&mut self, ui: &mut egui::Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Time:");
|
||||
ui.add(egui::DragValue::new(&mut self.image_settings.time)
|
||||
.speed(0.01)
|
||||
.range(0.0..=f64::MAX)
|
||||
.suffix(" s"));
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
ui.weak("Exports vector layers losslessly at this frame. Raster, video, and");
|
||||
ui.weak("effect layers are not included.");
|
||||
}
|
||||
|
||||
/// Render advanced image export settings (time, resolution override).
|
||||
fn render_image_advanced(&mut self, ui: &mut egui::Ui) {
|
||||
// Time (which frame to export)
|
||||
@@ -378,6 +401,19 @@ impl ExportDialog {
|
||||
if changed_h { self.image_settings.height = if h == 0 { None } else { Some(h) }; }
|
||||
ui.weak("(0 = document size)");
|
||||
});
|
||||
|
||||
// Fit mode — how the document maps into the output frame when aspect ratios differ.
|
||||
ui.horizontal(|ui| {
|
||||
use lightningbeam_core::export::ExportFitMode;
|
||||
ui.label("Fit:");
|
||||
egui::ComboBox::from_id_salt("image_fit_mode")
|
||||
.selected_text(self.image_settings.fit.name())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.image_settings.fit, ExportFitMode::Letterbox, ExportFitMode::Letterbox.name());
|
||||
ui.selectable_value(&mut self.image_settings.fit, ExportFitMode::Crop, ExportFitMode::Crop.name());
|
||||
ui.selectable_value(&mut self.image_settings.fit, ExportFitMode::Stretch, ExportFitMode::Stretch.name());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Render advanced audio settings (sample rate, channels, bit depth, bitrate, time range)
|
||||
@@ -504,6 +540,19 @@ impl ExportDialog {
|
||||
}
|
||||
});
|
||||
|
||||
// Fit mode — how the document maps into the export frame when the aspect ratios differ.
|
||||
ui.horizontal(|ui| {
|
||||
use lightningbeam_core::export::ExportFitMode;
|
||||
ui.label("Fit:");
|
||||
egui::ComboBox::from_id_salt("video_fit_mode")
|
||||
.selected_text(self.video_settings.fit.name())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.video_settings.fit, ExportFitMode::Letterbox, ExportFitMode::Letterbox.name());
|
||||
ui.selectable_value(&mut self.video_settings.fit, ExportFitMode::Crop, ExportFitMode::Crop.name());
|
||||
ui.selectable_value(&mut self.video_settings.fit, ExportFitMode::Stretch, ExportFitMode::Stretch.name());
|
||||
});
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("FPS:");
|
||||
egui::ComboBox::from_id_salt("framerate")
|
||||
@@ -527,6 +576,36 @@ impl ExportDialog {
|
||||
});
|
||||
});
|
||||
|
||||
// Color range applies to H.264 (the VAAPI zero-copy encoder honors it). Limited/TV is the
|
||||
// compatible default; Full/PC only looks right in players that read the full-range tag.
|
||||
if matches!(self.video_settings.codec, VideoCodec::H264) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Color range:");
|
||||
egui::ComboBox::from_id_salt("video_color_range")
|
||||
.selected_text(self.video_settings.color_range.name())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.video_settings.color_range, ColorRange::Limited, ColorRange::Limited.name());
|
||||
ui.selectable_value(&mut self.video_settings.color_range, ColorRange::Full, ColorRange::Full.name());
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// HDR output: 10-bit BT.2020 PQ/HLG (HEVC). Forces H.265; software path (no zero-copy).
|
||||
ui.horizontal(|ui| {
|
||||
use lightningbeam_core::export::HdrExportMode;
|
||||
ui.label("Dynamic range:");
|
||||
egui::ComboBox::from_id_salt("video_hdr_mode")
|
||||
.selected_text(self.video_settings.hdr.name())
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut self.video_settings.hdr, HdrExportMode::Sdr, HdrExportMode::Sdr.name());
|
||||
ui.selectable_value(&mut self.video_settings.hdr, HdrExportMode::Pq, HdrExportMode::Pq.name());
|
||||
ui.selectable_value(&mut self.video_settings.hdr, HdrExportMode::Hlg, HdrExportMode::Hlg.name());
|
||||
});
|
||||
});
|
||||
if self.video_settings.hdr.is_hdr() {
|
||||
ui.label(egui::RichText::new("HDR exports as 10-bit HEVC (H.265), BT.2020.").weak().small());
|
||||
}
|
||||
|
||||
ui.checkbox(&mut self.include_audio, "Include Audio");
|
||||
|
||||
ui.add_space(8.0);
|
||||
@@ -539,7 +618,7 @@ impl ExportDialog {
|
||||
fn render_time_range(&mut self, ui: &mut egui::Ui) {
|
||||
let (start_time, end_time) = match self.export_type {
|
||||
ExportType::Audio => (&mut self.audio_settings.start_time, &mut self.audio_settings.end_time),
|
||||
ExportType::Image => return, // image uses a single time field, not a range
|
||||
ExportType::Image | ExportType::Svg => return, // single time field, not a range
|
||||
ExportType::Video => (&mut self.video_settings.start_time, &mut self.video_settings.end_time),
|
||||
};
|
||||
|
||||
@@ -613,6 +692,7 @@ impl ExportDialog {
|
||||
}
|
||||
Some(ExportResult::Image(self.image_settings.clone(), output_path))
|
||||
}
|
||||
ExportType::Svg => Some(ExportResult::Svg(self.image_settings.time, output_path)),
|
||||
ExportType::Audio => {
|
||||
// Validate audio settings
|
||||
if let Err(err) = self.audio_settings.validate() {
|
||||
@@ -721,7 +801,7 @@ impl ExportProgressDialog {
|
||||
|
||||
egui::Modal::new(egui::Id::new("export_progress_modal"))
|
||||
.show(ctx, |ui| {
|
||||
ui.set_width(400.0);
|
||||
ui.set_width(crate::mobile::dialog_width(ctx, 400.0));
|
||||
|
||||
ui.heading("Exporting...");
|
||||
ui.add_space(8.0);
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
//! 8.3 MB RGBA) and — more importantly — the per-frame CPU `rgba_to_yuv420p` (swscale)
|
||||
//! is eliminated.
|
||||
//!
|
||||
//! Color math is BT.709 **full-range** (JPEG range), matching the encoder color tags
|
||||
//! set in `setup_video_encoder` (`Space::BT709` + `Range::JPEG`).
|
||||
//! Color math is BT.709; the Y/chroma scale+offset (full vs limited range) is selected by
|
||||
//! the `full_range` flag and must match the encoder color tags set in `setup_video_encoder`.
|
||||
//!
|
||||
//! Output buffer layout (tight, little-endian byte packing into `array<u32>`):
|
||||
//! - `[0, W*H)` Y plane, row stride `W`
|
||||
@@ -30,15 +30,36 @@ pub fn yuv420p_len(width: u32, height: u32) -> usize {
|
||||
y + 2 * c
|
||||
}
|
||||
|
||||
/// `(y_offset, y_scale, chroma_offset, chroma_scale)` as fractions of 255, selecting
|
||||
/// limited (TV, 16–235 / 16–240) vs full (PC, 0–255) range. Mirrors `render_nv12`.
|
||||
fn range_params(full_range: bool) -> [f32; 4] {
|
||||
if full_range {
|
||||
[0.0, 1.0, 128.0 / 255.0, 1.0]
|
||||
} else {
|
||||
[16.0 / 255.0, 219.0 / 255.0, 128.0 / 255.0, 224.0 / 255.0]
|
||||
}
|
||||
}
|
||||
|
||||
/// GPU compute pipeline: `Rgba8Unorm` texture → tight planar YUV420p storage buffer.
|
||||
pub struct GpuYuv {
|
||||
y_pipeline: wgpu::ComputePipeline,
|
||||
uv_pipeline: wgpu::ComputePipeline,
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
range_buffer: wgpu::Buffer,
|
||||
}
|
||||
|
||||
impl GpuYuv {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
/// `full_range`: true → full/PC range (Y 0–255), false → limited/TV range (Y 16–235).
|
||||
/// The encoder must tag the stream to match (`setup_video_encoder`'s `full_range`).
|
||||
pub fn new(device: &wgpu::Device, full_range: bool) -> Self {
|
||||
use wgpu::util::DeviceExt;
|
||||
let params = range_params(full_range);
|
||||
let range_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("gpu_yuv_range"),
|
||||
contents: bytemuck::cast_slice(¶ms),
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("gpu_yuv_bgl"),
|
||||
entries: &[
|
||||
@@ -64,6 +85,17 @@ impl GpuYuv {
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// 2: range params (y_offset, y_scale, chroma_offset, chroma_scale)
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -93,6 +125,7 @@ impl GpuYuv {
|
||||
y_pipeline: mk("y_main"),
|
||||
uv_pipeline: mk("uv_main"),
|
||||
bind_group_layout,
|
||||
range_buffer,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -118,6 +151,7 @@ impl GpuYuv {
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(rgba_view) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: yuv_buffer.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: self.range_buffer.as_entire_binding() },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -142,12 +176,12 @@ impl GpuYuv {
|
||||
|
||||
/// CPU reference for the exact math/layout the shader produces — used by unit tests so
|
||||
/// the packing and BT.709 coefficients stay verifiable without a GPU.
|
||||
#[cfg(test)]
|
||||
fn cpu_reference(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
|
||||
fn cpu_reference(rgba: &[u8], width: u32, height: u32, full_range: bool) -> Vec<u8> {
|
||||
let w = width as usize;
|
||||
let h = height as usize;
|
||||
let cw = w / 2;
|
||||
let ch = h / 2;
|
||||
let [yo, ys, co, cs] = range_params(full_range);
|
||||
let mut out = vec![0u8; yuv420p_len(width, height)];
|
||||
let to_byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
let px = |x: usize, y: usize| {
|
||||
@@ -158,7 +192,8 @@ fn cpu_reference(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let p = px(x, y);
|
||||
out[y * w + x] = to_byte(0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]);
|
||||
let yy = 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2];
|
||||
out[y * w + x] = to_byte(yo + ys * yy);
|
||||
}
|
||||
}
|
||||
// U/V (2x2 average)
|
||||
@@ -172,19 +207,21 @@ fn cpu_reference(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
|
||||
acc[0] += p[0]; acc[1] += p[1]; acc[2] += p[2];
|
||||
}
|
||||
let a = [acc[0] / 4.0, acc[1] / 4.0, acc[2] / 4.0];
|
||||
let u = -0.1146 * a[0] - 0.3854 * a[1] + 0.5000 * a[2] + 0.5;
|
||||
let v = 0.5000 * a[0] - 0.4542 * a[1] - 0.0458 * a[2] + 0.5;
|
||||
out[y_size + cy * cw + cx] = to_byte(u);
|
||||
out[y_size + uv_size + cy * cw + cx] = to_byte(v);
|
||||
let uc = -0.1146 * a[0] - 0.3854 * a[1] + 0.5000 * a[2];
|
||||
let vc = 0.5000 * a[0] - 0.4542 * a[1] - 0.0458 * a[2];
|
||||
out[y_size + cy * cw + cx] = to_byte(co + cs * uc);
|
||||
out[y_size + uv_size + cy * cw + cx] = to_byte(co + cs * vc);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const SHADER: &str = r#"
|
||||
// RGBA -> tight planar YUV420p (BT.709 full-range), packed 4 bytes/u32.
|
||||
// RGBA -> tight planar YUV420p (BT.709), packed 4 bytes/u32.
|
||||
// rng = (y_offset, y_scale, chroma_offset, chroma_scale): selects limited vs full range.
|
||||
@group(0) @binding(0) var input_rgba: texture_2d<f32>;
|
||||
@group(0) @binding(1) var<storage, read_write> out_buf: array<u32>;
|
||||
@group(0) @binding(2) var<uniform> rng: vec4<f32>;
|
||||
|
||||
fn to_byte(v: f32) -> u32 { return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); }
|
||||
|
||||
@@ -201,7 +238,7 @@ fn y_main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
for (var i = 0u; i < 4u; i = i + 1u) {
|
||||
let c = textureLoad(input_rgba, vec2<u32>(x4 + i, y), 0).rgb;
|
||||
let yy = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
packed = packed | (to_byte(yy) << (8u * i));
|
||||
packed = packed | (to_byte(rng.x + rng.y * yy) << (8u * i));
|
||||
}
|
||||
out_buf[(y * w + x4) / 4u] = packed;
|
||||
}
|
||||
@@ -230,10 +267,11 @@ fn uv_main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let p01 = textureLoad(input_rgba, vec2<u32>(sx, sy + 1u), 0).rgb;
|
||||
let p11 = textureLoad(input_rgba, vec2<u32>(sx + 1u, sy + 1u), 0).rgb;
|
||||
let a = (p00 + p10 + p01 + p11) * 0.25;
|
||||
let u = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b + 0.5;
|
||||
let v = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b + 0.5;
|
||||
up = up | (to_byte(u) << (8u * i));
|
||||
vp = vp | (to_byte(v) << (8u * i));
|
||||
// Centered chroma in [-0.5, 0.5], then map to range via (offset + scale*coef).
|
||||
let uc = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b;
|
||||
let vc = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b;
|
||||
up = up | (to_byte(rng.z + rng.w * uc) << (8u * i));
|
||||
vp = vp | (to_byte(rng.z + rng.w * vc) << (8u * i));
|
||||
}
|
||||
out_buf[(y_size + cy * cw + cx4) / 4u] = up;
|
||||
out_buf[(y_size + uv_size + cy * cw + cx4) / 4u] = vp;
|
||||
@@ -264,14 +302,14 @@ mod tests {
|
||||
fn reference_known_colors() {
|
||||
// 8x2 solid white → Y≈255, U≈V≈128. Solid black → Y=0, U=V≈128.
|
||||
let white = vec![255u8; 8 * 2 * 4];
|
||||
let out = cpu_reference(&white, 8, 2);
|
||||
let out = cpu_reference(&white, 8, 2, true);
|
||||
let (cw, ch) = (4usize, 1usize);
|
||||
let y_size = 8 * 2;
|
||||
for &y in &out[..y_size] { assert!(y >= 254, "white Y={y}"); }
|
||||
for &u in &out[y_size..y_size + cw * ch] { assert!((u as i32 - 128).abs() <= 1, "white U={u}"); }
|
||||
|
||||
let black = vec![0u8; 8 * 2 * 4];
|
||||
let out = cpu_reference(&black, 8, 2);
|
||||
let out = cpu_reference(&black, 8, 2, true);
|
||||
for &y in &out[..y_size] { assert_eq!(y, 0); }
|
||||
for &v in &out[y_size + cw * ch..] { assert!((v as i32 - 128).abs() <= 1, "black V={v}"); }
|
||||
}
|
||||
@@ -280,7 +318,7 @@ mod tests {
|
||||
fn reference_red_bt709() {
|
||||
// Solid red (255,0,0): Y=0.2126*255≈54; V high, U low (full range).
|
||||
let red: Vec<u8> = (0..8 * 2).flat_map(|_| [255u8, 0, 0, 255]).collect();
|
||||
let out = cpu_reference(&red, 8, 2);
|
||||
let out = cpu_reference(&red, 8, 2, true);
|
||||
assert!((out[0] as i32 - 54).abs() <= 1, "red Y={}", out[0]);
|
||||
let y_size = 8 * 2;
|
||||
let u = out[y_size];
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
//! 10-bit HDR frame production for video export (isolated from the SDR readback pipeline).
|
||||
//!
|
||||
//! Takes the compositor's Rgba16Float HDR accumulator and produces YUV420P10LE planes:
|
||||
//! 1. GPU pass `linear_to_pq.wgsl` → PQ/HLG-encoded BT.2020 R'G'B' into an Rgba16Unorm texture
|
||||
//! (the expensive per-pixel transfer + gamut work).
|
||||
//! 2. Synchronous GPU→CPU readback of that texture.
|
||||
//! 3. CPU BT.2020 R'G'B'→Y'CbCr (limited range), 4:2:0 average, 10-bit little-endian pack.
|
||||
//!
|
||||
//! Synchronous (no triple-buffering); HDR export favors correctness/simplicity over throughput.
|
||||
|
||||
use lightningbeam_core::export::HdrExportMode;
|
||||
|
||||
/// Round up to the wgpu copy row alignment (256 bytes).
|
||||
fn align_256(n: u32) -> u32 {
|
||||
(n + 255) & !255
|
||||
}
|
||||
|
||||
pub struct HdrFramePipeline {
|
||||
width: u32,
|
||||
height: u32,
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
sampler: wgpu::Sampler,
|
||||
mode_buf: wgpu::Buffer,
|
||||
/// PQ/HLG-encoded BT.2020 R'G'B' (Rgba16Unorm) render target.
|
||||
enc_texture_view: wgpu::TextureView,
|
||||
enc_texture: wgpu::Texture,
|
||||
/// Staging buffer for readback; rows padded to 256-byte alignment.
|
||||
staging: wgpu::Buffer,
|
||||
padded_bytes_per_row: u32,
|
||||
}
|
||||
|
||||
impl HdrFramePipeline {
|
||||
pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("linear_to_pq_shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/linear_to_pq.wgsl").into()),
|
||||
});
|
||||
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("linear_to_pq_bgl"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("linear_to_pq_pl"),
|
||||
bind_group_layouts: &[&bind_group_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("linear_to_pq_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
// Rgba16Float (not Unorm) so no TEXTURE_FORMAT_16BIT_NORM feature is needed; PQ/HLG
|
||||
// values are in [0,1] where f16 has ~11 effective bits — ample for 10-bit output.
|
||||
format: wgpu::TextureFormat::Rgba16Float,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState::default(),
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("linear_to_pq_sampler"),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let mode_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("linear_to_pq_mode"),
|
||||
size: 16, // vec4<u32>
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let enc_texture = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("hdr_enc_texture"),
|
||||
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba16Float,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
|
||||
view_formats: &[],
|
||||
});
|
||||
let enc_texture_view = enc_texture.create_view(&Default::default());
|
||||
|
||||
let padded_bytes_per_row = align_256(width * 8); // Rgba16Unorm = 8 bytes/texel
|
||||
let staging = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("hdr_enc_staging"),
|
||||
size: (padded_bytes_per_row * height) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
pipeline,
|
||||
bind_group_layout,
|
||||
sampler,
|
||||
mode_buf,
|
||||
enc_texture_view,
|
||||
enc_texture,
|
||||
staging,
|
||||
padded_bytes_per_row,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode the composited HDR texture (`hdr_view`, Rgba16Float linear) to YUV420P10LE planes.
|
||||
pub fn render_to_yuv10(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
hdr_view: &wgpu::TextureView,
|
||||
mode: HdrExportMode,
|
||||
) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
|
||||
let mode_code: u32 = if matches!(mode, HdrExportMode::Hlg) { 1 } else { 0 };
|
||||
queue.write_buffer(&self.mode_buf, 0, bytemuck::cast_slice(&[mode_code, 0u32, 0, 0]));
|
||||
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("linear_to_pq_bg"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(hdr_view) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: self.mode_buf.as_entire_binding() },
|
||||
],
|
||||
});
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("hdr_frame_encoder"),
|
||||
});
|
||||
{
|
||||
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("linear_to_pq_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &self.enc_texture_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
});
|
||||
rp.set_pipeline(&self.pipeline);
|
||||
rp.set_bind_group(0, &bind_group, &[]);
|
||||
rp.draw(0..3, 0..1);
|
||||
}
|
||||
encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &self.enc_texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &self.staging,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(self.padded_bytes_per_row),
|
||||
rows_per_image: Some(self.height),
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d { width: self.width, height: self.height, depth_or_array_layers: 1 },
|
||||
);
|
||||
queue.submit(Some(encoder.finish()));
|
||||
|
||||
// Synchronous map + wait.
|
||||
let slice = self.staging.slice(..);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
slice.map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); });
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let _ = rx.recv();
|
||||
|
||||
let w = self.width as usize;
|
||||
let h = self.height as usize;
|
||||
let mapped = slice.get_mapped_range();
|
||||
// Un-pad rows; decode f16 → f32 into a tight RGBA buffer.
|
||||
let mut rgba = vec![0f32; w * h * 4];
|
||||
let row_bytes = w * 8;
|
||||
for row in 0..h {
|
||||
let src = row * self.padded_bytes_per_row as usize;
|
||||
let dst = row * w * 4;
|
||||
let bytes = &mapped[src..src + row_bytes];
|
||||
for px in 0..w * 4 {
|
||||
let half = u16::from_le_bytes([bytes[px * 2], bytes[px * 2 + 1]]);
|
||||
rgba[dst + px] = f16_to_f32(half);
|
||||
}
|
||||
}
|
||||
drop(mapped);
|
||||
self.staging.unmap();
|
||||
|
||||
rgba_to_yuv420p10le(&rgba, w, h)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode an IEEE 754 half-float. Inputs are in [0,1] so the inf/NaN paths don't occur in practice.
|
||||
fn f16_to_f32(h: u16) -> f32 {
|
||||
let sign = (h >> 15) & 1;
|
||||
let exp = (h >> 10) & 0x1f;
|
||||
let mant = h & 0x3ff;
|
||||
let v = if exp == 0 {
|
||||
(mant as f32) * 2f32.powi(-24) // subnormal
|
||||
} else if exp == 31 {
|
||||
if mant == 0 { f32::INFINITY } else { f32::NAN }
|
||||
} else {
|
||||
(1.0 + mant as f32 / 1024.0) * 2f32.powi(exp as i32 - 15)
|
||||
};
|
||||
if sign == 1 { -v } else { v }
|
||||
}
|
||||
|
||||
/// BT.2020 non-constant-luminance R'G'B'→Y'CbCr, limited range, 4:2:0, 10-bit little-endian.
|
||||
/// Input R'G'B' is already gamma-encoded (PQ/HLG) in [0,1].
|
||||
fn rgba_to_yuv420p10le(rgba: &[f32], w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
|
||||
const KR: f32 = 0.2627;
|
||||
const KB: f32 = 0.0593;
|
||||
let kg = 1.0 - KR - KB;
|
||||
|
||||
let luma = |r: f32, g: f32, b: f32| KR * r + kg * g + KB * b;
|
||||
// 10-bit limited: Y' [64,940] (scale 876), Cb/Cr center 512, excursion ±0.5 → scale 896.
|
||||
let pack_y = |y: f32| ((y * 876.0 + 64.0).round().clamp(0.0, 1023.0)) as u16;
|
||||
let pack_c = |c: f32| ((c * 896.0 + 512.0).round().clamp(0.0, 1023.0)) as u16;
|
||||
|
||||
let mut y_plane = vec![0u8; w * h * 2];
|
||||
for j in 0..h {
|
||||
for i in 0..w {
|
||||
let p = (j * w + i) * 4;
|
||||
let y10 = pack_y(luma(rgba[p], rgba[p + 1], rgba[p + 2]));
|
||||
let o = (j * w + i) * 2;
|
||||
y_plane[o] = (y10 & 0xff) as u8;
|
||||
y_plane[o + 1] = (y10 >> 8) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
let (cw, ch) = (w / 2, h / 2);
|
||||
let mut u_plane = vec![0u8; cw * ch * 2];
|
||||
let mut v_plane = vec![0u8; cw * ch * 2];
|
||||
for j in 0..ch {
|
||||
for i in 0..cw {
|
||||
let (mut cb, mut cr) = (0.0f32, 0.0f32);
|
||||
for dy in 0..2 {
|
||||
for dx in 0..2 {
|
||||
let p = ((j * 2 + dy) * w + (i * 2 + dx)) * 4;
|
||||
let (r, g, b) = (rgba[p], rgba[p + 1], rgba[p + 2]);
|
||||
let yy = luma(r, g, b);
|
||||
cb += (b - yy) / (2.0 * (1.0 - KB));
|
||||
cr += (r - yy) / (2.0 * (1.0 - KR));
|
||||
}
|
||||
}
|
||||
let cb10 = pack_c(cb / 4.0);
|
||||
let cr10 = pack_c(cr / 4.0);
|
||||
let o = (j * cw + i) * 2;
|
||||
u_plane[o] = (cb10 & 0xff) as u8;
|
||||
u_plane[o + 1] = (cb10 >> 8) as u8;
|
||||
v_plane[o] = (cr10 & 0xff) as u8;
|
||||
v_plane[o + 1] = (cr10 >> 8) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
(y_plane, u_plane, v_plane)
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod readback_pipeline;
|
||||
pub mod perf_metrics;
|
||||
pub mod cpu_yuv_converter;
|
||||
pub mod gpu_yuv;
|
||||
pub mod hdr_frame;
|
||||
|
||||
use lightningbeam_core::export::{AudioExportSettings, ImageExportSettings, VideoExportSettings, ExportProgress};
|
||||
use lightningbeam_core::document::Document;
|
||||
@@ -52,6 +53,13 @@ pub struct VideoExportState {
|
||||
width: u32,
|
||||
/// Export height in pixels
|
||||
height: u32,
|
||||
/// HDR output mode — HDR uses a synchronous 10-bit path instead of the async RGBA pipeline.
|
||||
hdr: lightningbeam_core::export::HdrExportMode,
|
||||
/// How the document is fit into the export frame (stretch/letterbox/crop).
|
||||
fit: lightningbeam_core::export::ExportFitMode,
|
||||
/// SDR color range: true = full (PC, 0–255), false = limited (TV, 16–235). The YUV
|
||||
/// converters and the encoder color tag must agree on this.
|
||||
full_range: bool,
|
||||
/// Channel to send rendered frames to encoder thread
|
||||
frame_tx: Option<Sender<VideoFrameMessage>>,
|
||||
/// HDR GPU resources for compositing pipeline (effects, color conversion)
|
||||
@@ -79,6 +87,10 @@ struct ZeroCopyVideo {
|
||||
gpu_resources: video_exporter::ExportGpuResources,
|
||||
/// Reused RGBA target (RENDER_ATTACHMENT | TEXTURE_BINDING) on the encoder's device.
|
||||
rgba: wgpu::Texture,
|
||||
/// True when running on the shared device → compositing can consume hardware-decoded GPU frames.
|
||||
on_shared_device: bool,
|
||||
/// How the document is fit into the export frame (stretch/letterbox/crop).
|
||||
fit: lightningbeam_core::export::ExportFitMode,
|
||||
}
|
||||
|
||||
/// State for a single-frame image export (runs on the GPU render thread, one frame per update).
|
||||
@@ -589,6 +601,7 @@ impl ExportOrchestrator {
|
||||
// ── First call: render the frame to the GPU output texture ────────
|
||||
let w = state.width;
|
||||
let h = state.height;
|
||||
let fit = state.settings.fit;
|
||||
|
||||
if state.gpu_resources.is_none() {
|
||||
state.gpu_resources = Some(video_exporter::ExportGpuResources::new(device, w, h));
|
||||
@@ -622,6 +635,8 @@ impl ExportOrchestrator {
|
||||
floating_selection,
|
||||
state.settings.allow_transparency,
|
||||
raster_store,
|
||||
true, // image export composites on the shared device
|
||||
fit,
|
||||
)?;
|
||||
queue.submit(Some(encoder.finish()));
|
||||
|
||||
@@ -854,6 +869,9 @@ impl ExportOrchestrator {
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> (std::thread::JoinHandle<()>, VideoExportState) {
|
||||
let hdr = settings.hdr;
|
||||
let fit = settings.fit;
|
||||
let full_range = settings.color_range.is_full();
|
||||
let handle = std::thread::spawn(move || {
|
||||
Self::run_video_encoder(settings, output_path, frame_rx, progress_tx, cancel_flag, total_frames);
|
||||
});
|
||||
@@ -866,6 +884,9 @@ impl ExportOrchestrator {
|
||||
framerate,
|
||||
width,
|
||||
height,
|
||||
hdr,
|
||||
fit,
|
||||
full_range,
|
||||
frame_tx: Some(frame_tx),
|
||||
gpu_resources: None,
|
||||
readback_pipeline: None,
|
||||
@@ -889,17 +910,35 @@ impl ExportOrchestrator {
|
||||
height: u32,
|
||||
framerate: f64,
|
||||
output_path: &std::path::Path,
|
||||
shared_device: Option<(wgpu::Device, wgpu::Queue, wgpu::Adapter)>,
|
||||
) -> Option<ZeroCopyVideo> {
|
||||
if !matches!(settings.codec, lightningbeam_core::export::VideoCodec::H264) {
|
||||
// Zero-copy is 8-bit H.264 only; HDR needs the 10-bit HEVC software path.
|
||||
if settings.hdr.is_hdr()
|
||||
|| !matches!(settings.codec, lightningbeam_core::export::VideoCodec::H264)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let encoder = match gpu_video_encoder::encoder::ZeroCopyEncoder::new(
|
||||
width,
|
||||
height,
|
||||
framerate.round() as i32,
|
||||
settings.quality.bitrate_kbps(),
|
||||
output_path,
|
||||
) {
|
||||
let bitrate = settings.quality.bitrate_kbps();
|
||||
let fr = framerate.round() as i32;
|
||||
let full = settings.color_range.is_full();
|
||||
println!("🎬 [EXPORT] zero-copy H.264 color range: {} (full_range={})",
|
||||
settings.color_range.name(), full);
|
||||
let on_shared_device = shared_device.is_some();
|
||||
// Prefer the shared device → decode→composite→encode stay GPU-resident on one device.
|
||||
// Without it, the encoder builds its own device (decode still downloads to CPU per Step 1's
|
||||
// hardware_ok=false on this path).
|
||||
let encoder_result = match shared_device {
|
||||
Some((device, queue, adapter)) => {
|
||||
println!("🎬 [EXPORT] zero-copy on shared device (GPU-resident decode)");
|
||||
gpu_video_encoder::encoder::ZeroCopyEncoder::new_on_device(
|
||||
device, queue, adapter, width, height, fr, bitrate, output_path, full,
|
||||
)
|
||||
}
|
||||
None => gpu_video_encoder::encoder::ZeroCopyEncoder::new(
|
||||
width, height, fr, bitrate, output_path, full,
|
||||
),
|
||||
};
|
||||
let encoder = match encoder_result {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
println!("🎬 [EXPORT] zero-copy unavailable ({e}); software path");
|
||||
@@ -935,7 +974,7 @@ impl ExportOrchestrator {
|
||||
view_formats: &[],
|
||||
});
|
||||
println!("🎬 [EXPORT] zero-copy VAAPI H.264 enabled");
|
||||
Some(ZeroCopyVideo { encoder, renderer, gpu_resources, rgba })
|
||||
Some(ZeroCopyVideo { encoder, renderer, gpu_resources, rgba, on_shared_device, fit: settings.fit })
|
||||
}
|
||||
|
||||
/// Start a video export in the background.
|
||||
@@ -953,6 +992,7 @@ impl ExportOrchestrator {
|
||||
/// # Returns
|
||||
/// Ok(()) on success, Err on failure
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn start_video_export(
|
||||
&mut self,
|
||||
settings: VideoExportSettings,
|
||||
@@ -961,6 +1001,8 @@ impl ExportOrchestrator {
|
||||
video_manager: Arc<std::sync::Mutex<VideoManager>>,
|
||||
raster_store: lightningbeam_core::raster_store::RasterStore,
|
||||
container_path: Option<PathBuf>,
|
||||
// The shared VAAPI device, `Some` only when active → zero-copy encode runs on it.
|
||||
shared_device: Option<(wgpu::Device, wgpu::Queue, wgpu::Adapter)>,
|
||||
) -> Result<(), String> {
|
||||
println!("🎬 [VIDEO EXPORT] Starting video export");
|
||||
|
||||
@@ -988,7 +1030,7 @@ impl ExportOrchestrator {
|
||||
// success it returns here; otherwise we fall through to the software encoder thread.
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if let Some(zc) = Self::try_build_zero_copy(&settings, width, height, framerate, &output_path) {
|
||||
if let Some(zc) = Self::try_build_zero_copy(&settings, width, height, framerate, &output_path, shared_device) {
|
||||
drop(frame_rx);
|
||||
let document_snapshot = document.clone();
|
||||
let mut image_cache = ImageCache::new();
|
||||
@@ -1052,6 +1094,8 @@ impl ExportOrchestrator {
|
||||
video_manager: Arc<std::sync::Mutex<VideoManager>>,
|
||||
raster_store: lightningbeam_core::raster_store::RasterStore,
|
||||
container_path: Option<PathBuf>,
|
||||
// The shared VAAPI device, `Some` only when active → zero-copy encode runs on it.
|
||||
shared_device: Option<(wgpu::Device, wgpu::Queue, wgpu::Adapter)>,
|
||||
) -> Result<(), String> {
|
||||
println!("🎬🎵 [PARALLEL EXPORT] Starting parallel video+audio export");
|
||||
|
||||
@@ -1118,7 +1162,7 @@ impl ExportOrchestrator {
|
||||
// by `render_next_video_frame` on the UI thread.
|
||||
#[cfg(target_os = "linux")]
|
||||
let (video_thread, video_state) = match Self::try_build_zero_copy(
|
||||
&video_settings, video_width, video_height, video_framerate, &temp_video_path,
|
||||
&video_settings, video_width, video_height, video_framerate, &temp_video_path, shared_device,
|
||||
) {
|
||||
Some(zc) => {
|
||||
drop(frame_rx); // the zero-copy path renders internally, no frame channel
|
||||
@@ -1241,6 +1285,44 @@ impl ExportOrchestrator {
|
||||
|
||||
let width = state.width;
|
||||
let height = state.height;
|
||||
let fit = state.fit;
|
||||
|
||||
// HDR path: synchronous 10-bit render (composite → PQ/HLG → readback → 10-bit YUV), one
|
||||
// frame per call. Bypasses the SDR async RGBA pipeline (which is 8-bit only).
|
||||
if state.hdr.is_hdr() {
|
||||
if state.gpu_resources.is_none() {
|
||||
println!("🎬 [VIDEO EXPORT] Initializing HDR GPU resources {}x{} ({})", width, height, state.hdr.name());
|
||||
state.gpu_resources = Some(video_exporter::ExportGpuResources::new(device, width, height));
|
||||
}
|
||||
if state.current_frame < state.total_frames {
|
||||
let timestamp = state.start_time + (state.current_frame as f64 / state.framerate);
|
||||
let gpu_resources = state.gpu_resources.as_mut().unwrap();
|
||||
let (y, u, v) = video_exporter::render_frame_to_yuv10_hdr(
|
||||
document, timestamp, width, height,
|
||||
device, queue, renderer, image_cache, video_manager,
|
||||
gpu_resources, state.hdr, fit, raster_store,
|
||||
)?;
|
||||
if let Some(tx) = &state.frame_tx {
|
||||
tx.send(VideoFrameMessage::Frame {
|
||||
frame_num: state.current_frame,
|
||||
timestamp,
|
||||
y_plane: y,
|
||||
u_plane: u,
|
||||
v_plane: v,
|
||||
}).map_err(|_| "Failed to send HDR frame")?;
|
||||
}
|
||||
state.current_frame += 1;
|
||||
}
|
||||
if state.current_frame >= state.total_frames {
|
||||
println!("🎬 [VIDEO EXPORT] HDR complete: {} frames", state.total_frames);
|
||||
if let Some(tx) = state.frame_tx.take() {
|
||||
tx.send(VideoFrameMessage::Done).ok();
|
||||
}
|
||||
state.gpu_resources = None;
|
||||
return Ok(false);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
// Initialize GPU resources and readback pipeline on first frame
|
||||
if state.gpu_resources.is_none() {
|
||||
@@ -1258,8 +1340,8 @@ impl ExportOrchestrator {
|
||||
if !gpu_yuv_tight {
|
||||
println!("🎬 [VIDEO EXPORT] YUV planes are padded at {width}x{height}; using CPU YUV path");
|
||||
}
|
||||
state.readback_pipeline = Some(readback_pipeline::ReadbackPipeline::new(device, queue, width, height, gpu_yuv_tight));
|
||||
state.cpu_yuv_converter = Some(cpu_yuv_converter::CpuYuvConverter::new(width, height)?);
|
||||
state.readback_pipeline = Some(readback_pipeline::ReadbackPipeline::new(device, queue, width, height, gpu_yuv_tight, state.full_range));
|
||||
state.cpu_yuv_converter = Some(cpu_yuv_converter::CpuYuvConverter::new(width, height, state.full_range)?);
|
||||
println!("🚀 [ASYNC PIPELINE] Triple-buffered pipeline initialized");
|
||||
println!("🚀 [CPU YUV] swscale converter initialized");
|
||||
}
|
||||
@@ -1347,6 +1429,8 @@ impl ExportOrchestrator {
|
||||
None, // No floating selection during video export
|
||||
false, // Video export is never transparent
|
||||
raster_store,
|
||||
true, // software export composites on the shared device → may use HW frames
|
||||
fit,
|
||||
)?;
|
||||
let render_end = Instant::now();
|
||||
|
||||
@@ -1437,6 +1521,7 @@ impl ExportOrchestrator {
|
||||
let rgba_view = zc.rgba.create_view(&Default::default());
|
||||
|
||||
let t0 = std::time::Instant::now();
|
||||
let fit = zc.fit;
|
||||
let cmd = match video_exporter::render_frame_to_gpu_rgba(
|
||||
&mut document,
|
||||
timestamp,
|
||||
@@ -1452,6 +1537,8 @@ impl ExportOrchestrator {
|
||||
None,
|
||||
false,
|
||||
Some(&raster_store),
|
||||
zc.on_shared_device, // GPU-resident decode only when on the shared device
|
||||
fit,
|
||||
) {
|
||||
Ok(cmd) => cmd,
|
||||
Err(e) => {
|
||||
@@ -1555,13 +1642,33 @@ impl ExportOrchestrator {
|
||||
// Initialize FFmpeg
|
||||
ffmpeg_next::init().map_err(|e| format!("Failed to initialize FFmpeg: {}", e))?;
|
||||
|
||||
// Convert codec enum to FFmpeg codec ID
|
||||
let codec_id = match settings.codec {
|
||||
VideoCodec::H264 => ffmpeg_next::codec::Id::H264,
|
||||
VideoCodec::H265 => ffmpeg_next::codec::Id::HEVC,
|
||||
VideoCodec::VP8 => ffmpeg_next::codec::Id::VP8,
|
||||
VideoCodec::VP9 => ffmpeg_next::codec::Id::VP9,
|
||||
VideoCodec::ProRes422 => ffmpeg_next::codec::Id::PRORES,
|
||||
// Convert codec enum to FFmpeg codec ID. HDR requires 10-bit HEVC (Main10), so force HEVC
|
||||
// regardless of the chosen codec when an HDR mode is selected.
|
||||
let codec_id = if settings.hdr.is_hdr() {
|
||||
// HEVC can only be muxed into MP4/MOV, not WebM — reject the incompatible combo up
|
||||
// front with a clear message instead of letting the muxer fail cryptically.
|
||||
if settings.codec.container_format() == "webm" {
|
||||
return Err(format!(
|
||||
"HDR export needs H.265/HEVC in an MP4 container, but {} uses WebM. \
|
||||
Pick H.265 (or H.264) for HDR.",
|
||||
settings.codec.name()
|
||||
));
|
||||
}
|
||||
if !matches!(settings.codec, VideoCodec::H265) {
|
||||
println!(
|
||||
"⚠️ [ENCODER] HDR selected: overriding codec {} → H.265/HEVC (Main10)",
|
||||
settings.codec.name()
|
||||
);
|
||||
}
|
||||
ffmpeg_next::codec::Id::HEVC
|
||||
} else {
|
||||
match settings.codec {
|
||||
VideoCodec::H264 => ffmpeg_next::codec::Id::H264,
|
||||
VideoCodec::H265 => ffmpeg_next::codec::Id::HEVC,
|
||||
VideoCodec::VP8 => ffmpeg_next::codec::Id::VP8,
|
||||
VideoCodec::VP9 => ffmpeg_next::codec::Id::VP9,
|
||||
VideoCodec::ProRes422 => ffmpeg_next::codec::Id::PRORES,
|
||||
}
|
||||
};
|
||||
|
||||
// Get bitrate from quality settings
|
||||
@@ -1604,8 +1711,17 @@ impl ExportOrchestrator {
|
||||
height,
|
||||
framerate,
|
||||
bitrate_kbps,
|
||||
settings.hdr,
|
||||
settings.color_range.is_full(),
|
||||
)?;
|
||||
|
||||
// Pixel format the encoder frames are built in (matches setup_video_encoder).
|
||||
let pixel_format = if settings.hdr.is_hdr() {
|
||||
ffmpeg_next::format::Pixel::YUV420P10LE
|
||||
} else {
|
||||
ffmpeg_next::format::Pixel::YUV420P
|
||||
};
|
||||
|
||||
// Create output file
|
||||
let mut output = ffmpeg_next::format::output(&output_path)
|
||||
.map_err(|e| format!("Failed to create output file: {}", e))?;
|
||||
@@ -1634,6 +1750,7 @@ impl ExportOrchestrator {
|
||||
width,
|
||||
height,
|
||||
timestamp,
|
||||
pixel_format,
|
||||
)?;
|
||||
|
||||
// Send progress update for first frame
|
||||
@@ -1661,6 +1778,7 @@ impl ExportOrchestrator {
|
||||
width,
|
||||
height,
|
||||
timestamp,
|
||||
pixel_format,
|
||||
)?;
|
||||
|
||||
frames_encoded += 1;
|
||||
@@ -1705,29 +1823,33 @@ impl ExportOrchestrator {
|
||||
width: u32,
|
||||
height: u32,
|
||||
timestamp: f64,
|
||||
pixel_format: ffmpeg_next::format::Pixel,
|
||||
) -> Result<(), String> {
|
||||
// YUV planes already converted by GPU (no CPU conversion needed)
|
||||
// YUV planes already converted (8-bit YUV420P, or 10-bit YUV420P10LE for HDR).
|
||||
|
||||
// Create FFmpeg video frame
|
||||
let mut video_frame = ffmpeg_next::frame::Video::new(
|
||||
ffmpeg_next::format::Pixel::YUV420P,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
// Create FFmpeg video frame in the encoder's pixel format.
|
||||
let mut video_frame = ffmpeg_next::frame::Video::new(pixel_format, width, height);
|
||||
|
||||
// Copy YUV planes to frame
|
||||
// Use safe slice copy - LLVM optimizes this to memcpy, same performance as copy_nonoverlapping
|
||||
let y_dest = video_frame.data_mut(0);
|
||||
let y_len = y_plane.len().min(y_dest.len());
|
||||
y_dest[..y_len].copy_from_slice(&y_plane[..y_len]);
|
||||
|
||||
let u_dest = video_frame.data_mut(1);
|
||||
let u_len = u_plane.len().min(u_dest.len());
|
||||
u_dest[..u_len].copy_from_slice(&u_plane[..u_len]);
|
||||
|
||||
let v_dest = video_frame.data_mut(2);
|
||||
let v_len = v_plane.len().min(v_dest.len());
|
||||
v_dest[..v_len].copy_from_slice(&v_plane[..v_len]);
|
||||
// Copy each plane row-by-row honoring the frame's stride (10-bit / arbitrary widths can have
|
||||
// row padding that a flat copy would misalign). `bytes_per_row` = samples × sample size.
|
||||
let ten_bit = matches!(pixel_format, ffmpeg_next::format::Pixel::YUV420P10LE);
|
||||
let sample_bytes = if ten_bit { 2usize } else { 1usize };
|
||||
let copy_plane = |frame: &mut ffmpeg_next::frame::Video, idx: usize, src: &[u8], w: usize, h: usize| {
|
||||
let bytes_per_row = w * sample_bytes;
|
||||
let stride = frame.stride(idx);
|
||||
let dst = frame.data_mut(idx);
|
||||
for row in 0..h {
|
||||
let s = row * bytes_per_row;
|
||||
let d = row * stride;
|
||||
let n = bytes_per_row.min(src.len().saturating_sub(s)).min(dst.len().saturating_sub(d));
|
||||
if n == 0 { break; }
|
||||
dst[d..d + n].copy_from_slice(&src[s..s + n]);
|
||||
}
|
||||
};
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
copy_plane(&mut video_frame, 0, y_plane, w, h);
|
||||
copy_plane(&mut video_frame, 1, u_plane, w / 2, h / 2);
|
||||
copy_plane(&mut video_frame, 2, v_plane, w / 2, h / 2);
|
||||
|
||||
// Set PTS (presentation timestamp) in encoder's time base
|
||||
// Encoder time base is 1/(framerate * 1000), so PTS = timestamp * (framerate * 1000)
|
||||
|
||||
@@ -91,12 +91,12 @@ impl ReadbackPipeline {
|
||||
/// `enable_gpu_yuv` should be `true` only when the caller has verified the encoder's
|
||||
/// `YUV420P` plane strides are tight (== width / width-2), so the packed GPU planes
|
||||
/// drop straight into the `AVFrame` without row misalignment.
|
||||
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32, enable_gpu_yuv: bool) -> Self {
|
||||
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32, enable_gpu_yuv: bool, full_range: bool) -> Self {
|
||||
let (readback_tx, readback_rx) = channel();
|
||||
|
||||
// GPU YUV conversion when enabled AND the dimensions fit the packed shader; else RGBA + CPU.
|
||||
let gpu_yuv = if enable_gpu_yuv && super::gpu_yuv::supports(width, height) {
|
||||
Some(super::gpu_yuv::GpuYuv::new(device))
|
||||
Some(super::gpu_yuv::GpuYuv::new(device, full_range))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// Linear-HDR → PQ/HLG BT.2020 encode (for 10-bit HDR video export).
|
||||
//
|
||||
// Input: the compositor's Rgba16Float HDR accumulator — PREMULTIPLIED scene-linear, BT.709
|
||||
// primaries, graphics white = 1.0, HDR highlights > 1.0.
|
||||
// Output: gamma-encoded R'G'B' in BT.2020 primaries, PQ (mode 0) or HLG (mode 1), to an
|
||||
// Rgba16Unorm target. A later CPU pass does only BT.2020 R'G'B'→Y'CbCr (no transfer) + 4:2:0 + 10-bit.
|
||||
//
|
||||
// This is the encode inverse of panes/shaders/nv12_blit.wgsl's decode (203-nit PQ white; HLG
|
||||
// reference white at signal 0.75), so a decode→encode round-trip is the identity.
|
||||
|
||||
@group(0) @binding(0) var input_tex: texture_2d<f32>;
|
||||
@group(0) @binding(1) var input_sampler: sampler;
|
||||
@group(0) @binding(2) var<uniform> params: vec4<u32>; // .x = mode (0 = PQ, 1 = HLG)
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
let x = f32((vertex_index & 1u) << 1u);
|
||||
let y = f32(vertex_index & 2u);
|
||||
out.position = vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
|
||||
out.uv = vec2<f32>(x, y);
|
||||
return out;
|
||||
}
|
||||
|
||||
// BT.709 → BT.2020 primaries, linear light (ITU-R BT.2087).
|
||||
fn bt709_to_bt2020(c: vec3<f32>) -> vec3<f32> {
|
||||
let r = 0.627404 * c.r + 0.329283 * c.g + 0.043313 * c.b;
|
||||
let g = 0.069097 * c.r + 0.919540 * c.g + 0.011362 * c.b;
|
||||
let b = 0.016391 * c.r + 0.088013 * c.g + 0.895595 * c.b;
|
||||
return vec3<f32>(r, g, b);
|
||||
}
|
||||
|
||||
// SMPTE ST 2084 (PQ) OETF: scene-linear (white = 1.0 = 203 nits) → PQ code [0,1].
|
||||
fn pq_oetf(lin: vec3<f32>) -> vec3<f32> {
|
||||
let nits = max(lin, vec3<f32>(0.0)) * 203.0;
|
||||
let ln = min(nits / 10000.0, vec3<f32>(1.0));
|
||||
let m1 = 0.1593017578125;
|
||||
let m2 = 78.84375;
|
||||
let c1 = 0.8359375;
|
||||
let c2 = 18.8515625;
|
||||
let c3 = 18.6875;
|
||||
let lm = pow(ln, vec3<f32>(m1));
|
||||
return pow((vec3<f32>(c1) + c2 * lm) / (vec3<f32>(1.0) + c3 * lm), vec3<f32>(m2));
|
||||
}
|
||||
|
||||
// ARIB STD-B67 (HLG) OETF: scene-linear (white = 1.0) → HLG signal [0,1]. Reference white maps to
|
||||
// signal 0.75 (matching the decode's /0.26496256 normalization). Display OOTF omitted (scene-referred).
|
||||
fn hlg_oetf(lin: vec3<f32>) -> vec3<f32> {
|
||||
let a = 0.17883277;
|
||||
let b = 0.28466892;
|
||||
let c = 0.55991073;
|
||||
let e = clamp(lin * 0.26496256, vec3<f32>(0.0), vec3<f32>(1.0));
|
||||
let lo = sqrt(3.0 * e);
|
||||
let hi = a * log(12.0 * e - vec3<f32>(b)) + vec3<f32>(c);
|
||||
return select(lo, hi, e > vec3<f32>(1.0 / 12.0));
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
// Compositor stores PREMULTIPLIED linear; unpremultiply to straight (video is opaque, a≈1).
|
||||
let texel = textureSample(input_tex, input_sampler, in.uv);
|
||||
let a = texel.a;
|
||||
let straight = select(texel.rgb / a, vec3<f32>(0.0), a <= 0.0);
|
||||
|
||||
let bt2020 = max(bt709_to_bt2020(straight), vec3<f32>(0.0));
|
||||
var enc: vec3<f32>;
|
||||
if params.x == 1u {
|
||||
enc = hlg_oetf(bt2020);
|
||||
} else {
|
||||
enc = pq_oetf(bt2020);
|
||||
}
|
||||
return vec4<f32>(enc, 1.0);
|
||||
}
|
||||
@@ -16,6 +16,30 @@ use lightningbeam_core::gpu::{
|
||||
SrgbToLinearConverter, EffectProcessor, YuvConverter, HDR_FORMAT,
|
||||
};
|
||||
|
||||
/// The document→export-pixels transform for a given fit mode. Stretch distorts to fill; Letterbox
|
||||
/// scales uniformly to fit (centered, black bars); Crop scales uniformly to fill (centered, trims).
|
||||
pub fn export_base_transform(
|
||||
doc_w: f64,
|
||||
doc_h: f64,
|
||||
out_w: f64,
|
||||
out_h: f64,
|
||||
fit: lightningbeam_core::export::ExportFitMode,
|
||||
) -> vello::kurbo::Affine {
|
||||
use lightningbeam_core::export::ExportFitMode;
|
||||
use vello::kurbo::Affine;
|
||||
if doc_w <= 0.0 || doc_h <= 0.0 {
|
||||
return Affine::IDENTITY;
|
||||
}
|
||||
let (sx, sy) = (out_w / doc_w, out_h / doc_h);
|
||||
match fit {
|
||||
ExportFitMode::Stretch => Affine::scale_non_uniform(sx, sy),
|
||||
ExportFitMode::Letterbox | ExportFitMode::Crop => {
|
||||
let s = if matches!(fit, ExportFitMode::Letterbox) { sx.min(sy) } else { sx.max(sy) };
|
||||
Affine::translate(((out_w - doc_w * s) / 2.0, (out_h - doc_h * s) / 2.0)) * Affine::scale(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable frame buffers to avoid allocations
|
||||
struct FrameBuffers {
|
||||
/// RGBA buffer from GPU readback (width * height * 4 bytes)
|
||||
@@ -75,14 +99,25 @@ pub struct ExportGpuResources {
|
||||
pub staging_buffer: wgpu::Buffer,
|
||||
/// Linear to sRGB blit pipeline for final output
|
||||
pub linear_to_srgb_pipeline: wgpu::RenderPipeline,
|
||||
/// Variant with highlight rolloff (document HDR output mode = Highlight rolloff).
|
||||
pub linear_to_srgb_pipeline_rolloff: wgpu::RenderPipeline,
|
||||
/// Bind group layout for linear to sRGB blit
|
||||
pub linear_to_srgb_bind_group_layout: wgpu::BindGroupLayout,
|
||||
/// Sampler for linear to sRGB conversion
|
||||
pub linear_to_srgb_sampler: wgpu::Sampler,
|
||||
/// Canvas blit pipeline for raster/video/float layers (bypasses Vello).
|
||||
pub canvas_blit: crate::gpu_brush::CanvasBlitPipeline,
|
||||
/// NV12→linear blit for hardware-decoded video frames (export on the shared device).
|
||||
pub nv12_blit: crate::nv12_blit::Nv12BlitPipeline,
|
||||
/// Per-keyframe GPU texture cache for raster layers during export.
|
||||
pub raster_cache: std::collections::HashMap<uuid::Uuid, crate::gpu_brush::CanvasPair>,
|
||||
/// Cached HDR accumulator state after the (static) background is composited in. The document
|
||||
/// background doesn't change across an export, so it's rendered once and restored with a cheap
|
||||
/// texture copy each frame instead of a full Vello render + 2 passes/submits. `None` until the
|
||||
/// first frame; invalidated on resize.
|
||||
cached_bg_hdr: Option<wgpu::Texture>,
|
||||
/// HDR encode pipeline (linear→PQ/HLG BT.2020 → 10-bit YUV). Lazily built on the first HDR frame.
|
||||
hdr_pipeline: Option<super::hdr_frame::HdrFramePipeline>,
|
||||
}
|
||||
|
||||
impl ExportGpuResources {
|
||||
@@ -108,7 +143,8 @@ impl ExportGpuResources {
|
||||
format: HDR_FORMAT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_SRC,
|
||||
| wgpu::TextureUsages::COPY_SRC
|
||||
| wgpu::TextureUsages::COPY_DST, // restore cached background each frame
|
||||
view_formats: &[],
|
||||
});
|
||||
let hdr_texture_view = hdr_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
@@ -230,6 +266,41 @@ impl ExportGpuResources {
|
||||
cache: None,
|
||||
});
|
||||
|
||||
// Highlight-rolloff variant: identical but the `fs_main_rolloff` entry point.
|
||||
let linear_to_srgb_pipeline_rolloff = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("linear_to_srgb_pipeline_rolloff"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main_rolloff"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleStrip,
|
||||
strip_index_format: None,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: None,
|
||||
polygon_mode: wgpu::PolygonMode::Fill,
|
||||
unclipped_depth: false,
|
||||
conservative: false,
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
let linear_to_srgb_sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("linear_to_srgb_sampler"),
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
@@ -242,6 +313,7 @@ impl ExportGpuResources {
|
||||
});
|
||||
|
||||
let canvas_blit = crate::gpu_brush::CanvasBlitPipeline::new(device);
|
||||
let nv12_blit = crate::nv12_blit::Nv12BlitPipeline::new(device);
|
||||
|
||||
Self {
|
||||
buffer_pool,
|
||||
@@ -257,10 +329,14 @@ impl ExportGpuResources {
|
||||
yuv_texture_view,
|
||||
staging_buffer,
|
||||
linear_to_srgb_pipeline,
|
||||
linear_to_srgb_pipeline_rolloff,
|
||||
linear_to_srgb_bind_group_layout,
|
||||
linear_to_srgb_sampler,
|
||||
canvas_blit,
|
||||
nv12_blit,
|
||||
raster_cache: std::collections::HashMap::new(),
|
||||
cached_bg_hdr: None,
|
||||
hdr_pipeline: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,10 +355,12 @@ impl ExportGpuResources {
|
||||
format: HDR_FORMAT,
|
||||
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_SRC,
|
||||
| wgpu::TextureUsages::COPY_SRC
|
||||
| wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
self.hdr_texture_view = self.hdr_texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.cached_bg_hdr = None; // dimensions changed — rebuild the background cache
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,6 +409,32 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
|
||||
return vec4<f32>(srgb, a);
|
||||
}
|
||||
|
||||
// Highlight rolloff: identity below the knee, smooth C1 rolloff [knee,∞)→[knee,1) above (recovers
|
||||
// super-white HDR detail). SDR below the knee is untouched. Mirrors panes/shaders/linear_to_srgb.wgsl.
|
||||
fn highlight_rolloff_ch(x: f32) -> f32 {
|
||||
let knee = 0.8;
|
||||
if x <= knee {
|
||||
return x;
|
||||
}
|
||||
let headroom = 1.0 - knee;
|
||||
return knee + headroom * (1.0 - exp(-(x - knee) / headroom));
|
||||
}
|
||||
|
||||
// Variant of fs_main with highlight rolloff (document HDR output mode = Highlight rolloff).
|
||||
@fragment
|
||||
fn fs_main_rolloff(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let src = textureSample(source_tex, source_sampler, in.uv);
|
||||
let a = src.a;
|
||||
let straight = select(src.rgb / a, vec3<f32>(0.0), a <= 0.0);
|
||||
let rolled = vec3<f32>(
|
||||
highlight_rolloff_ch(straight.r),
|
||||
highlight_rolloff_ch(straight.g),
|
||||
highlight_rolloff_ch(straight.b),
|
||||
);
|
||||
let srgb = linear_to_srgb(rolled);
|
||||
return vec4<f32>(srgb, a);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Convert RGBA8 pixels to YUV420p format using BT.709 color space
|
||||
@@ -455,6 +559,8 @@ pub fn setup_video_encoder(
|
||||
height: u32,
|
||||
framerate: f64,
|
||||
bitrate_kbps: u32,
|
||||
hdr: lightningbeam_core::export::HdrExportMode,
|
||||
full_range: bool,
|
||||
) -> Result<(ffmpeg::encoder::Video, ffmpeg::Codec), String> {
|
||||
// Try to find codec by ID first
|
||||
println!("🔍 Looking for codec: {:?}", codec_id);
|
||||
@@ -510,31 +616,46 @@ pub fn setup_video_encoder(
|
||||
// Configure encoder parameters BEFORE opening (critical!)
|
||||
encoder.set_width(aligned_width);
|
||||
encoder.set_height(aligned_height);
|
||||
encoder.set_format(ffmpeg::format::Pixel::YUV420P);
|
||||
// HDR encodes 10-bit BT.2020 (limited range); SDR keeps 8-bit full-range BT.709.
|
||||
if hdr.is_hdr() {
|
||||
encoder.set_format(ffmpeg::format::Pixel::YUV420P10LE);
|
||||
} else {
|
||||
encoder.set_format(ffmpeg::format::Pixel::YUV420P);
|
||||
}
|
||||
encoder.set_time_base(ffmpeg::Rational(1, (framerate * 1000.0) as i32));
|
||||
encoder.set_frame_rate(Some(ffmpeg::Rational(framerate as i32, 1)));
|
||||
encoder.set_bit_rate((bitrate_kbps * 1000) as usize);
|
||||
encoder.set_gop(framerate as u32); // 1 second GOP
|
||||
|
||||
// Tag the color metadata so players interpret the YUV correctly. Our
|
||||
// RGB→YUV conversion uses the BT.709 matrix with FULL-range (0–255) luma
|
||||
// and no transfer applied to the already-sRGB-encoded RGB. Tagging this
|
||||
// as full-range BT.709 (matrix/primaries/transfer) prevents the level/
|
||||
// hue shift that occurs when a player assumes limited-range or BT.601.
|
||||
// colorspace (matrix) and range have safe setters; primaries and trc are
|
||||
// generic AVCodecContext options set via the open dictionary below.
|
||||
encoder.set_colorspace(ffmpeg::color::Space::BT709);
|
||||
encoder.set_color_range(ffmpeg::color::Range::JPEG); // full range
|
||||
|
||||
println!("📐 Video dimensions: {}×{} (aligned to {}×{} for H.264)",
|
||||
width, height, aligned_width, aligned_height);
|
||||
|
||||
// Open encoder with codec (like working MP3 export). color_primaries and
|
||||
// color_trc have no typed setter on the encoder, so pass them as generic
|
||||
// AVCodecContext options (BT.709) through the open dictionary.
|
||||
// Tag the color metadata so players interpret the YUV correctly.
|
||||
// SDR: our RGB→YUV uses the BT.709 matrix with FULL-range (0–255) luma and no transfer applied
|
||||
// to the already-sRGB-encoded RGB, so tag full-range BT.709 to avoid level/hue shifts.
|
||||
// HDR: BT.2020 non-constant-luminance matrix, LIMITED range (standard for HDR10/HLG), with the
|
||||
// PQ or HLG transfer; the 10-bit YUV is produced from PQ/HLG-encoded BT.2020 RGB.
|
||||
let mut color_opts = ffmpeg::Dictionary::new();
|
||||
color_opts.set("color_primaries", "bt709");
|
||||
color_opts.set("color_trc", "bt709");
|
||||
if hdr.is_hdr() {
|
||||
encoder.set_colorspace(ffmpeg::color::Space::BT2020NCL);
|
||||
encoder.set_color_range(ffmpeg::color::Range::MPEG); // limited
|
||||
color_opts.set("color_primaries", "bt2020");
|
||||
color_opts.set("color_trc", hdr.transfer_name());
|
||||
// HEVC 10-bit profile (the only HDR-capable codec we wire up).
|
||||
color_opts.set("profile", "main10");
|
||||
} else {
|
||||
encoder.set_colorspace(ffmpeg::color::Space::BT709);
|
||||
// Range must match what the YUV converters (gpu_yuv / cpu_yuv) actually produce.
|
||||
encoder.set_color_range(if full_range {
|
||||
ffmpeg::color::Range::JPEG // full (PC, 0–255)
|
||||
} else {
|
||||
ffmpeg::color::Range::MPEG // limited (TV, 16–235)
|
||||
});
|
||||
color_opts.set("color_primaries", "bt709");
|
||||
color_opts.set("color_trc", "bt709");
|
||||
}
|
||||
|
||||
println!("📐 Video dimensions: {}×{} (aligned to {}×{}){}",
|
||||
width, height, aligned_width, aligned_height,
|
||||
if hdr.is_hdr() { " [HDR 10-bit BT.2020]" } else { "" });
|
||||
|
||||
let encoder = encoder
|
||||
.open_as_with(codec, color_opts)
|
||||
.map_err(|e| format!("Failed to open video encoder: {}", e))?;
|
||||
@@ -748,29 +869,74 @@ fn composite_document_to_hdr(
|
||||
antialiasing_method: vello::AaConfig::Area,
|
||||
};
|
||||
|
||||
// --- Background ---
|
||||
let bg_srgb = gpu_resources.buffer_pool.acquire(device, layer_spec);
|
||||
let bg_hdr = gpu_resources.buffer_pool.acquire(device, hdr_spec);
|
||||
if let (Some(bg_srgb_view), Some(bg_hdr_view)) = (
|
||||
gpu_resources.buffer_pool.get_view(bg_srgb),
|
||||
gpu_resources.buffer_pool.get_view(bg_hdr),
|
||||
) {
|
||||
renderer.render_to_texture(device, queue, &composite_result.background, bg_srgb_view, &layer_render_params)
|
||||
.map_err(|e| format!("Failed to render background: {e}"))?;
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export_bg_srgb_to_linear") });
|
||||
gpu_resources.srgb_to_linear.convert(device, &mut enc, bg_srgb_view, bg_hdr_view);
|
||||
let prof = render_profile_enabled();
|
||||
let t_c0 = std::time::Instant::now();
|
||||
|
||||
// --- Background (cached) ---
|
||||
// The document background is static across an export, so render it through Vello exactly once
|
||||
// (into the accumulator) and snapshot the result; every later frame restores it with a single
|
||||
// GPU texture copy instead of a Vello render + sRGB-convert + composite (+2 submits).
|
||||
let bg_cached = matches!(
|
||||
&gpu_resources.cached_bg_hdr,
|
||||
Some(t) if t.width() == width && t.height() == height
|
||||
);
|
||||
let copy_size = wgpu::Extent3d { width, height, depth_or_array_layers: 1 };
|
||||
if bg_cached {
|
||||
// Restore the cached background into the accumulator.
|
||||
let cached = gpu_resources.cached_bg_hdr.as_ref().unwrap();
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export_bg_restore") });
|
||||
enc.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: cached, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyTextureInfo { texture: &gpu_resources.hdr_texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
copy_size,
|
||||
);
|
||||
queue.submit(Some(enc.finish()));
|
||||
let bg_layer = CompositorLayer::normal(bg_hdr, 1.0);
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export_bg_composite") });
|
||||
// When transparency is allowed, start from transparent black so the background's
|
||||
// native alpha is preserved. Otherwise force an opaque black underlay.
|
||||
let clear = if allow_transparency { [0.0, 0.0, 0.0, 0.0] } else { [0.0, 0.0, 0.0, 1.0] };
|
||||
gpu_resources.compositor.composite(device, queue, &mut enc, &[bg_layer],
|
||||
&gpu_resources.buffer_pool, &gpu_resources.hdr_texture_view, Some(clear));
|
||||
} else {
|
||||
// First frame (or after a resize): full background render into the accumulator.
|
||||
let bg_srgb = gpu_resources.buffer_pool.acquire(device, layer_spec);
|
||||
let bg_hdr = gpu_resources.buffer_pool.acquire(device, hdr_spec);
|
||||
if let (Some(bg_srgb_view), Some(bg_hdr_view)) = (
|
||||
gpu_resources.buffer_pool.get_view(bg_srgb),
|
||||
gpu_resources.buffer_pool.get_view(bg_hdr),
|
||||
) {
|
||||
renderer.render_to_texture(device, queue, &composite_result.background, bg_srgb_view, &layer_render_params)
|
||||
.map_err(|e| format!("Failed to render background: {e}"))?;
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export_bg_srgb_to_linear") });
|
||||
gpu_resources.srgb_to_linear.convert(device, &mut enc, bg_srgb_view, bg_hdr_view);
|
||||
queue.submit(Some(enc.finish()));
|
||||
let bg_layer = CompositorLayer::normal(bg_hdr, 1.0);
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export_bg_composite") });
|
||||
// When transparency is allowed, start from transparent black so the background's
|
||||
// native alpha is preserved. Otherwise force an opaque black underlay.
|
||||
let clear = if allow_transparency { [0.0, 0.0, 0.0, 0.0] } else { [0.0, 0.0, 0.0, 1.0] };
|
||||
gpu_resources.compositor.composite(device, queue, &mut enc, &[bg_layer],
|
||||
&gpu_resources.buffer_pool, &gpu_resources.hdr_texture_view, Some(clear));
|
||||
queue.submit(Some(enc.finish()));
|
||||
}
|
||||
gpu_resources.buffer_pool.release(bg_srgb);
|
||||
gpu_resources.buffer_pool.release(bg_hdr);
|
||||
|
||||
// Snapshot the composited background for reuse on subsequent frames.
|
||||
let cached = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("export_cached_bg_hdr"),
|
||||
size: copy_size,
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: HDR_FORMAT,
|
||||
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export_bg_snapshot") });
|
||||
enc.copy_texture_to_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: &gpu_resources.hdr_texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyTextureInfo { texture: &cached, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
copy_size,
|
||||
);
|
||||
queue.submit(Some(enc.finish()));
|
||||
gpu_resources.cached_bg_hdr = Some(cached);
|
||||
}
|
||||
gpu_resources.buffer_pool.release(bg_srgb);
|
||||
gpu_resources.buffer_pool.release(bg_hdr);
|
||||
let t_bg = std::time::Instant::now();
|
||||
|
||||
// --- Layers ---
|
||||
for rendered_layer in &composite_result.layers {
|
||||
@@ -827,16 +993,26 @@ fn composite_document_to_hdr(
|
||||
}
|
||||
RenderedLayerType::Video { instances } => {
|
||||
for inst in instances {
|
||||
if inst.rgba_data.is_empty() { continue; }
|
||||
if inst.gpu.is_none() && inst.rgba_data.is_empty() { continue; }
|
||||
let hdr_layer_handle = gpu_resources.buffer_pool.acquire(device, hdr_spec);
|
||||
if let Some(hdr_layer_view) = gpu_resources.buffer_pool.get_view(hdr_layer_handle) {
|
||||
// Upload raw sRGB straight-alpha bytes into an sRGB texture; the GPU
|
||||
// decodes to linear on sample (no per-pixel CPU conversion). Blit with
|
||||
// blit_straight so the shader doesn't unpremultiply.
|
||||
let tex = upload_transient_texture(device, queue, &inst.rgba_data, inst.width, inst.height, wgpu::TextureFormat::Rgba8UnormSrgb, Some("export_video_frame_tex"));
|
||||
let tex_view = tex.create_view(&Default::default());
|
||||
let bt = crate::gpu_brush::BlitTransform::new(inst.transform, inst.width, inst.height, width, height);
|
||||
gpu_resources.canvas_blit.blit_straight(device, queue, &tex_view, hdr_layer_view, &bt, None);
|
||||
if let Some(gpu) = &inst.gpu {
|
||||
// Hardware-decoded NV12 plane textures → linear, no CPU upload.
|
||||
let y_view = gpu.y.create_view(&Default::default());
|
||||
let uv_view = gpu.uv.create_view(&Default::default());
|
||||
gpu_resources.nv12_blit.blit(
|
||||
device, queue, &y_view, &uv_view, hdr_layer_view, &bt,
|
||||
gpu.full_range, gpu.coeffs, gpu.transfer, gpu.primaries,
|
||||
);
|
||||
} else {
|
||||
// Upload raw sRGB straight-alpha bytes into an sRGB texture; the GPU
|
||||
// decodes to linear on sample (no per-pixel CPU conversion). Blit with
|
||||
// blit_straight so the shader doesn't unpremultiply.
|
||||
let tex = upload_transient_texture(device, queue, &inst.rgba_data, inst.width, inst.height, wgpu::TextureFormat::Rgba8UnormSrgb, Some("export_video_frame_tex"));
|
||||
let tex_view = tex.create_view(&Default::default());
|
||||
gpu_resources.canvas_blit.blit_straight(device, queue, &tex_view, hdr_layer_view, &bt, None);
|
||||
}
|
||||
let compositor_layer = CompositorLayer::new(hdr_layer_handle, inst.opacity, lightningbeam_core::gpu::BlendMode::Normal);
|
||||
let mut enc = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("export_video_composite") });
|
||||
gpu_resources.compositor.composite(device, queue, &mut enc, &[compositor_layer], &gpu_resources.buffer_pool, &gpu_resources.hdr_texture_view, None);
|
||||
@@ -906,10 +1082,33 @@ fn composite_document_to_hdr(
|
||||
}
|
||||
}
|
||||
|
||||
if prof {
|
||||
record_composite_profile(t_bg.duration_since(t_c0), t_bg.elapsed());
|
||||
}
|
||||
|
||||
gpu_resources.buffer_pool.next_frame();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Split of `composite_document_to_hdr`: static-background re-render vs. the layer loop
|
||||
/// (video upload + blits). Prints a running average every 200 frames under LB_RENDER_PROFILE.
|
||||
fn record_composite_profile(background: std::time::Duration, layers: std::time::Duration) {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static BG_US: AtomicU64 = AtomicU64::new(0);
|
||||
static LAYERS_US: AtomicU64 = AtomicU64::new(0);
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
BG_US.fetch_add(background.as_micros() as u64, Ordering::Relaxed);
|
||||
LAYERS_US.fetch_add(layers.as_micros() as u64, Ordering::Relaxed);
|
||||
let n = N.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n % 200 == 0 {
|
||||
println!(
|
||||
"📊 [COMPOSITE PROFILE] {n} frames avg: background-render {:.2}ms | layers(video upload+blit) {:.2}ms",
|
||||
BG_US.load(Ordering::Relaxed) as f64 / n as f64 / 1000.0,
|
||||
LAYERS_US.load(Ordering::Relaxed) as f64 / n as f64 / 1000.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Upload `pixels` to a transient GPU texture (TEXTURE_BINDING | COPY_DST) in the
|
||||
/// given format. Use `Rgba8UnormSrgb` to upload raw sRGB bytes and let the GPU
|
||||
/// decode to linear on sample (no CPU conversion).
|
||||
@@ -940,221 +1139,9 @@ fn upload_transient_texture(
|
||||
tex
|
||||
}
|
||||
|
||||
/// Render a document frame using the HDR compositing pipeline with effects
|
||||
///
|
||||
/// This function uses the same rendering pipeline as the stage preview,
|
||||
/// ensuring effects are applied correctly during export.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `document` - Document to render (current_time will be modified)
|
||||
/// * `timestamp` - Time in seconds to render at
|
||||
/// * `width` - Frame width in pixels
|
||||
/// * `height` - Frame height in pixels
|
||||
/// * `device` - wgpu device
|
||||
/// * `queue` - wgpu queue
|
||||
/// * `renderer` - Vello renderer
|
||||
/// * `image_cache` - Image cache for rendering
|
||||
/// * `video_manager` - Video manager for video clips
|
||||
/// * `gpu_resources` - HDR GPU resources for compositing
|
||||
///
|
||||
/// # Returns
|
||||
/// Ok((y_plane, u_plane, v_plane)) with YUV420p planes on success, Err with message on failure
|
||||
pub fn render_frame_to_rgba_hdr(
|
||||
document: &mut Document,
|
||||
timestamp: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
renderer: &mut vello::Renderer,
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &Arc<std::sync::Mutex<VideoManager>>,
|
||||
gpu_resources: &mut ExportGpuResources,
|
||||
) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), String> {
|
||||
use vello::kurbo::Affine;
|
||||
|
||||
// Set document time to the frame timestamp
|
||||
document.current_time = timestamp;
|
||||
|
||||
// Scale the document to the export resolution. The core renderer bakes this
|
||||
// base transform into every layer (vector scenes, raster and video layer
|
||||
// transforms), so the whole stage scales up/down to fill the output. When the
|
||||
// export size matches the document this is the identity.
|
||||
let base_transform = if document.width > 0.0 && document.height > 0.0 {
|
||||
Affine::scale_non_uniform(
|
||||
width as f64 / document.width,
|
||||
height as f64 / document.height,
|
||||
)
|
||||
} else {
|
||||
Affine::IDENTITY
|
||||
};
|
||||
|
||||
// Render document for compositing (returns per-layer scenes)
|
||||
let composite_result = render_document_for_compositing(
|
||||
document,
|
||||
base_transform,
|
||||
image_cache,
|
||||
video_manager,
|
||||
None, // No webcam during export
|
||||
None, // No floating selection during export
|
||||
false, // No checkerboard in export
|
||||
);
|
||||
|
||||
// Video export is never transparent.
|
||||
composite_document_to_hdr(&composite_result, document, device, queue, renderer, gpu_resources, width, height, false)?;
|
||||
|
||||
// Use persistent output texture (already created in ExportGpuResources)
|
||||
let output_view = &gpu_resources.output_texture_view;
|
||||
|
||||
// Convert HDR to sRGB for output
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("export_linear_to_srgb_bind_group"),
|
||||
layout: &gpu_resources.linear_to_srgb_bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(&gpu_resources.hdr_texture_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: wgpu::BindingResource::Sampler(&gpu_resources.linear_to_srgb_sampler),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("export_linear_to_srgb_encoder"),
|
||||
});
|
||||
|
||||
{
|
||||
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("export_linear_to_srgb_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &output_view,
|
||||
resolve_target: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
depth_slice: None,
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
render_pass.set_pipeline(&gpu_resources.linear_to_srgb_pipeline);
|
||||
render_pass.set_bind_group(0, &bind_group, &[]);
|
||||
render_pass.draw(0..4, 0..1);
|
||||
}
|
||||
|
||||
queue.submit(Some(encoder.finish()));
|
||||
|
||||
// GPU YUV conversion: Convert RGBA output to YUV420p
|
||||
let mut yuv_encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("export_yuv_conversion_encoder"),
|
||||
});
|
||||
|
||||
gpu_resources.yuv_converter.convert(
|
||||
device,
|
||||
&mut yuv_encoder,
|
||||
output_view,
|
||||
&gpu_resources.yuv_texture_view,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
|
||||
// Copy YUV texture to persistent staging buffer
|
||||
let yuv_height = height + height / 2; // Y plane + U plane + V plane
|
||||
yuv_encoder.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &gpu_resources.yuv_texture,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &gpu_resources.staging_buffer,
|
||||
layout: wgpu::TexelCopyBufferLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: Some(width * 4), // Rgba8Unorm = 4 bytes per pixel
|
||||
rows_per_image: Some(yuv_height),
|
||||
},
|
||||
},
|
||||
wgpu::Extent3d {
|
||||
width,
|
||||
height: yuv_height,
|
||||
depth_or_array_layers: 1,
|
||||
},
|
||||
);
|
||||
|
||||
queue.submit(Some(yuv_encoder.finish()));
|
||||
|
||||
// Map buffer and read YUV pixels (synchronous)
|
||||
let buffer_slice = gpu_resources.staging_buffer.slice(..);
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||
sender.send(result).ok();
|
||||
});
|
||||
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
receiver
|
||||
.recv()
|
||||
.map_err(|_| "Failed to receive buffer mapping result")?
|
||||
.map_err(|e| format!("Failed to map buffer: {:?}", e))?;
|
||||
|
||||
// Extract Y, U, V planes from packed YUV buffer
|
||||
let data = buffer_slice.get_mapped_range();
|
||||
let width_usize = width as usize;
|
||||
let height_usize = height as usize;
|
||||
|
||||
// Y plane: rows 0 to height-1 (extract R channel from Rgba8Unorm)
|
||||
let y_plane_size = width_usize * height_usize;
|
||||
let mut y_plane = vec![0u8; y_plane_size];
|
||||
for y in 0..height_usize {
|
||||
let src_row_offset = y * width_usize * 4; // 4 bytes per pixel (Rgba8Unorm)
|
||||
let dst_row_offset = y * width_usize;
|
||||
for x in 0..width_usize {
|
||||
y_plane[dst_row_offset + x] = data[src_row_offset + x * 4]; // Extract R channel
|
||||
}
|
||||
}
|
||||
|
||||
// U and V planes: rows height to height + height/2 - 1 (half resolution, side-by-side layout)
|
||||
// U plane is in left half (columns 0 to width/2-1), V plane is in right half (columns width/2 to width-1)
|
||||
let chroma_width = width_usize / 2;
|
||||
let chroma_height = height_usize / 2;
|
||||
let chroma_row_start = height_usize * width_usize * 4; // Start of chroma rows in bytes
|
||||
|
||||
let mut u_plane = vec![0u8; chroma_width * chroma_height];
|
||||
let mut v_plane = vec![0u8; chroma_width * chroma_height];
|
||||
|
||||
for y in 0..chroma_height {
|
||||
let row_offset = chroma_row_start + y * width_usize * 4; // Full width rows in chroma region
|
||||
|
||||
// Extract U plane (left half: columns 0 to chroma_width-1)
|
||||
let u_start = row_offset;
|
||||
let dst_offset = y * chroma_width;
|
||||
for x in 0..chroma_width {
|
||||
u_plane[dst_offset + x] = data[u_start + x * 4]; // Extract R channel
|
||||
}
|
||||
|
||||
// Extract V plane (right half: columns width/2 to width/2+chroma_width-1)
|
||||
let v_start = row_offset + chroma_width * 4;
|
||||
for x in 0..chroma_width {
|
||||
v_plane[dst_offset + x] = data[v_start + x * 4]; // Extract R channel
|
||||
}
|
||||
}
|
||||
|
||||
drop(data);
|
||||
gpu_resources.staging_buffer.unmap();
|
||||
|
||||
Ok((y_plane, u_plane, v_plane))
|
||||
}
|
||||
|
||||
/// Render frame to GPU RGBA texture (non-blocking, for async pipeline)
|
||||
///
|
||||
/// Similar to render_frame_to_rgba_hdr but renders to an external RGBA texture view
|
||||
/// Renders to an external RGBA texture view
|
||||
/// (provided by ReadbackPipeline) and returns the command encoder WITHOUT blocking on readback.
|
||||
/// The caller (ReadbackPipeline) will submit the encoder and handle async readback.
|
||||
///
|
||||
@@ -1206,6 +1193,51 @@ fn fault_in_raster_for_frame(
|
||||
}
|
||||
}
|
||||
|
||||
/// Render one frame as 10-bit HDR YUV420P10LE planes (BT.2020 + PQ/HLG). Synchronous: composites,
|
||||
/// runs the linear→PQ/HLG GPU pass, reads it back, and CPU-converts to 10-bit YUV. Used by the
|
||||
/// HDR export path instead of the async readback pipeline.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn render_frame_to_yuv10_hdr(
|
||||
document: &mut Document,
|
||||
timestamp: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
renderer: &mut vello::Renderer,
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &Arc<std::sync::Mutex<VideoManager>>,
|
||||
gpu_resources: &mut ExportGpuResources,
|
||||
hdr_mode: lightningbeam_core::export::HdrExportMode,
|
||||
fit: lightningbeam_core::export::ExportFitMode,
|
||||
raster_store: Option<&lightningbeam_core::raster_store::RasterStore>,
|
||||
) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), String> {
|
||||
document.current_time = timestamp;
|
||||
fault_in_raster_for_frame(document, raster_store);
|
||||
|
||||
let base_transform = export_base_transform(document.width, document.height, width as f64, height as f64, fit);
|
||||
|
||||
// HDR export composites on the shared device, so it can consume hardware-decoded GPU frames.
|
||||
if let Ok(mut vm) = video_manager.lock() {
|
||||
vm.set_render_hardware_ok(true);
|
||||
}
|
||||
|
||||
let composite_result = render_document_for_compositing(
|
||||
document, base_transform, image_cache, video_manager, None, None, false,
|
||||
);
|
||||
composite_document_to_hdr(&composite_result, document, device, queue, renderer, gpu_resources, width, height, false)?;
|
||||
|
||||
if gpu_resources.hdr_pipeline.is_none() {
|
||||
gpu_resources.hdr_pipeline = Some(super::hdr_frame::HdrFramePipeline::new(device, width, height));
|
||||
}
|
||||
let planes = gpu_resources
|
||||
.hdr_pipeline
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.render_to_yuv10(device, queue, &gpu_resources.hdr_texture_view, hdr_mode);
|
||||
Ok(planes)
|
||||
}
|
||||
|
||||
pub fn render_frame_to_gpu_rgba(
|
||||
document: &mut Document,
|
||||
timestamp: f64,
|
||||
@@ -1221,8 +1253,16 @@ pub fn render_frame_to_gpu_rgba(
|
||||
floating_selection: Option<&lightningbeam_core::selection::RasterFloatingSelection>,
|
||||
allow_transparency: bool,
|
||||
raster_store: Option<&lightningbeam_core::raster_store::RasterStore>,
|
||||
// True when compositing on the shared device (software/image export) → may consume
|
||||
// hardware-decoded GPU frames; false for the zero-copy path on its own device.
|
||||
hardware_ok: bool,
|
||||
fit: lightningbeam_core::export::ExportFitMode,
|
||||
) -> Result<wgpu::CommandEncoder, String> {
|
||||
use vello::kurbo::Affine;
|
||||
// One-shot profiling of the render-bucket split (LB_RENDER_PROFILE=1): how much of the
|
||||
// per-frame CPU "render" is document build (incl. video decode) vs. composite-command
|
||||
// recording (incl. the frame texture upload) vs. the sRGB pass. Prints a running average.
|
||||
let prof = render_profile_enabled();
|
||||
let t0 = std::time::Instant::now();
|
||||
|
||||
// Set document time to the frame timestamp
|
||||
document.current_time = timestamp;
|
||||
@@ -1237,14 +1277,13 @@ pub fn render_frame_to_gpu_rgba(
|
||||
// base transform into every layer (vector scenes, raster and video layer
|
||||
// transforms), so the whole stage scales up/down to fill the output. When the
|
||||
// export size matches the document this is the identity.
|
||||
let base_transform = if document.width > 0.0 && document.height > 0.0 {
|
||||
Affine::scale_non_uniform(
|
||||
width as f64 / document.width,
|
||||
height as f64 / document.height,
|
||||
)
|
||||
} else {
|
||||
Affine::IDENTITY
|
||||
};
|
||||
let base_transform = export_base_transform(document.width, document.height, width as f64, height as f64, fit);
|
||||
|
||||
// GPU frames are usable only on the shared device (software/image export); the zero-copy path
|
||||
// runs on its own device and must download to CPU.
|
||||
if let Ok(mut vm) = video_manager.lock() {
|
||||
vm.set_render_hardware_ok(hardware_ok);
|
||||
}
|
||||
|
||||
// Render document for compositing (returns per-layer scenes)
|
||||
let composite_result = render_document_for_compositing(
|
||||
@@ -1256,8 +1295,10 @@ pub fn render_frame_to_gpu_rgba(
|
||||
floating_selection,
|
||||
false, // No checkerboard in export
|
||||
);
|
||||
let t_build = std::time::Instant::now();
|
||||
|
||||
composite_document_to_hdr(&composite_result, document, device, queue, renderer, gpu_resources, width, height, allow_transparency)?;
|
||||
let t_composite = std::time::Instant::now();
|
||||
|
||||
// Convert HDR to sRGB (linear → sRGB), render directly to external RGBA texture
|
||||
let output_view = rgba_texture_view;
|
||||
@@ -1297,16 +1338,58 @@ pub fn render_frame_to_gpu_rgba(
|
||||
timestamp_writes: None,
|
||||
});
|
||||
|
||||
render_pass.set_pipeline(&gpu_resources.linear_to_srgb_pipeline);
|
||||
let final_pipeline = match document.hdr_output_mode {
|
||||
lightningbeam_core::document::HdrOutputMode::HighlightRolloff => &gpu_resources.linear_to_srgb_pipeline_rolloff,
|
||||
lightningbeam_core::document::HdrOutputMode::Clip => &gpu_resources.linear_to_srgb_pipeline,
|
||||
};
|
||||
render_pass.set_pipeline(final_pipeline);
|
||||
render_pass.set_bind_group(0, &bind_group, &[]);
|
||||
render_pass.draw(0..4, 0..1);
|
||||
}
|
||||
|
||||
if prof {
|
||||
record_render_profile(
|
||||
t_build.duration_since(t0),
|
||||
t_composite.duration_since(t_build),
|
||||
t_composite.elapsed(),
|
||||
);
|
||||
}
|
||||
|
||||
// Return encoder for caller to submit (ReadbackPipeline will handle submission and async readback)
|
||||
// Frame is already rendered to external RGBA texture, no GPU YUV conversion needed
|
||||
Ok(encoder)
|
||||
}
|
||||
|
||||
/// `LB_RENDER_PROFILE` gate, checked once.
|
||||
fn render_profile_enabled() -> bool {
|
||||
static V: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*V.get_or_init(|| std::env::var("LB_RENDER_PROFILE").is_ok())
|
||||
}
|
||||
|
||||
/// Accumulate the per-frame render split and print a running average every 200 frames.
|
||||
/// `build` = document build incl. video decode; `composite` = composite-command recording
|
||||
/// incl. the frame texture upload; `srgb` = the linear→sRGB pass.
|
||||
fn record_render_profile(build: std::time::Duration, composite: std::time::Duration, srgb: std::time::Duration) {
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
static BUILD_US: AtomicU64 = AtomicU64::new(0);
|
||||
static COMPOSITE_US: AtomicU64 = AtomicU64::new(0);
|
||||
static SRGB_US: AtomicU64 = AtomicU64::new(0);
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
BUILD_US.fetch_add(build.as_micros() as u64, Ordering::Relaxed);
|
||||
COMPOSITE_US.fetch_add(composite.as_micros() as u64, Ordering::Relaxed);
|
||||
SRGB_US.fetch_add(srgb.as_micros() as u64, Ordering::Relaxed);
|
||||
let n = N.fetch_add(1, Ordering::Relaxed) + 1;
|
||||
if n % 200 == 0 {
|
||||
let (b, c, s) = (BUILD_US.load(Ordering::Relaxed), COMPOSITE_US.load(Ordering::Relaxed), SRGB_US.load(Ordering::Relaxed));
|
||||
println!(
|
||||
"📊 [RENDER PROFILE] {n} frames avg: build(+decode) {:.2}ms | composite(+upload) {:.2}ms | srgb {:.2}ms",
|
||||
b as f64 / n as f64 / 1000.0,
|
||||
c as f64 / n as f64 / 1000.0,
|
||||
s as f64 / n as f64 / 1000.0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -1627,12 +1627,24 @@ impl GpuBrushEngine {
|
||||
self.proxy_layer_cache.get(kf_id)
|
||||
}
|
||||
|
||||
/// Remove the cached texture for a raster layer keyframe (e.g. when deleted).
|
||||
/// Remove the cached texture for a raster layer keyframe (e.g. when deleted or edited).
|
||||
pub fn remove_layer_texture(&mut self, kf_id: &Uuid) {
|
||||
if self.raster_layer_cache.remove(kf_id).is_some() {
|
||||
let mut changed = self.raster_layer_cache.remove(kf_id).is_some();
|
||||
if changed {
|
||||
if let Some(pos) = self.raster_layer_lru.iter().position(|id| id == kf_id) {
|
||||
self.raster_layer_lru.remove(pos);
|
||||
}
|
||||
}
|
||||
// Also drop the low-res proxy: proxies are uploaded once and never refreshed, so a
|
||||
// stale pre-edit proxy left here would be blitted (flashing old content) if the full-res
|
||||
// texture is later evicted before the edited pixels page back in.
|
||||
if self.proxy_layer_cache.remove(kf_id).is_some() {
|
||||
if let Some(pos) = self.proxy_layer_lru.iter().position(|id| id == kf_id) {
|
||||
self.proxy_layer_lru.remove(pos);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
self.report_raster_cache_vram();
|
||||
}
|
||||
}
|
||||
@@ -2238,6 +2250,8 @@ impl CanvasBlitPipeline {
|
||||
/// Blit a **straight-alpha** source (e.g. a video frame uploaded to an
|
||||
/// `Rgba8UnormSrgb` texture, hardware-decoded to linear on sample). Uses the
|
||||
/// `fs_main_straight` pipeline, which skips the unpremultiply that `blit` does.
|
||||
/// Bilinear-sampled: video frames are scaled to the output size (document→export, or any
|
||||
/// non-1:1 transform), and nearest sampling makes that look blocky.
|
||||
pub fn blit_straight(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
@@ -2247,7 +2261,7 @@ impl CanvasBlitPipeline {
|
||||
transform: &BlitTransform,
|
||||
mask_view: Option<&wgpu::TextureView>,
|
||||
) {
|
||||
self.blit_with(device, queue, canvas_view, target_view, transform, mask_view, &self.sampler, &self.pipeline_straight);
|
||||
self.blit_with(device, queue, canvas_view, target_view, transform, mask_view, &self.linear_sampler, &self.pipeline_straight);
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Hardware video decode glue (Linux/VAAPI). The editor implements core's [`HwVideoImporter`]:
|
||||
//! it maps a decoded VAAPI surface to a DRM-PRIME DMA-BUF and imports it as wgpu NV12 plane
|
||||
//! textures on the **shared** device (the one eframe + the compositor run on, which has the
|
||||
//! DMA-BUF-import extensions). [`install`] creates the VAAPI device and wires it into the
|
||||
//! `VideoManager`.
|
||||
|
||||
use ffmpeg_next::ffi as ff;
|
||||
use gpu_video_encoder::dmabuf::{self, Nv12DmaBuf};
|
||||
use lightningbeam_core::video::{
|
||||
ycbcr_coeffs, GpuVideoFrame, HwDeviceHandle, HwVideoImporter, VideoManager, VideoPrimaries,
|
||||
VideoTransfer,
|
||||
};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Imports decoded VAAPI surfaces onto the shared wgpu device. Holds clones of the shared
|
||||
/// device + adapter (Arc-backed, cheap).
|
||||
struct SharedHwImporter {
|
||||
device: wgpu::Device,
|
||||
adapter: wgpu::Adapter,
|
||||
/// Log the detected colour info once (under LB_VIDEO_DEBUG) rather than per frame.
|
||||
logged: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
|
||||
impl HwVideoImporter for SharedHwImporter {
|
||||
unsafe fn import(&self, av_frame: *mut std::ffi::c_void) -> Option<GpuVideoFrame> {
|
||||
let frame = av_frame as *mut ff::AVFrame;
|
||||
|
||||
// Map the VAAPI surface to a DRM-PRIME DMA-BUF (read-only).
|
||||
let drm_f = ff::av_frame_alloc();
|
||||
(*drm_f).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
|
||||
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32 | ff::AV_HWFRAME_MAP_READ as i32;
|
||||
if ff::av_hwframe_map(drm_f, frame, flags) < 0 {
|
||||
ff::av_frame_free(&mut (drm_f as *mut _));
|
||||
return None;
|
||||
}
|
||||
|
||||
let desc = (*drm_f).data[0] as *const ff::AVDRMFrameDescriptor;
|
||||
let obj = &(*desc).objects[0];
|
||||
let width = (*frame).width as u32;
|
||||
let height = (*frame).height as u32;
|
||||
|
||||
// 10/12/16-bit content decodes to P010-style surfaces (16-bit planes). Detect via the hw
|
||||
// frames context's software format so the import builds R16/Rg16 textures.
|
||||
let ten_bit = {
|
||||
let hwfc = (*frame).hw_frames_ctx;
|
||||
if hwfc.is_null() {
|
||||
false
|
||||
} else {
|
||||
let ctx = (*hwfc).data as *const ff::AVHWFramesContext;
|
||||
matches!(
|
||||
(*ctx).sw_format,
|
||||
ff::AVPixelFormat::AV_PIX_FMT_P010LE
|
||||
| ff::AVPixelFormat::AV_PIX_FMT_P010BE
|
||||
| ff::AVPixelFormat::AV_PIX_FMT_P012LE
|
||||
| ff::AVPixelFormat::AV_PIX_FMT_P012BE
|
||||
| ff::AVPixelFormat::AV_PIX_FMT_P016LE
|
||||
| ff::AVPixelFormat::AV_PIX_FMT_P016BE
|
||||
)
|
||||
}
|
||||
};
|
||||
// NV12: Y then UV — two layers (one plane each) or one layer with two planes.
|
||||
let (y_pl, uv_pl) = if (*desc).nb_layers >= 2 {
|
||||
(&(*desc).layers[0].planes[0], &(*desc).layers[1].planes[0])
|
||||
} else {
|
||||
(&(*desc).layers[0].planes[0], &(*desc).layers[0].planes[1])
|
||||
};
|
||||
let buf = Nv12DmaBuf {
|
||||
fd: obj.fd,
|
||||
size: obj.size as u64,
|
||||
modifier: obj.format_modifier,
|
||||
width,
|
||||
height,
|
||||
y_offset: y_pl.offset as u64,
|
||||
y_pitch: y_pl.pitch as u64,
|
||||
uv_offset: uv_pl.offset as u64,
|
||||
uv_pitch: uv_pl.pitch as u64,
|
||||
ten_bit,
|
||||
};
|
||||
let full_range = (*frame).color_range == ff::AVColorRange::AVCOL_RANGE_JPEG;
|
||||
|
||||
// Luma weights (kr, kb) from the frame's matrix coefficients, so SD (BT.601) and HD/UHD
|
||||
// (BT.709) clips each convert with the right matrix. Unspecified → guess by height, as
|
||||
// players/swscale do. SMPTE240M and BT.2020 are handled too (the latter's transfer is still
|
||||
// approximated as sRGB — fine for SDR; true HDR is out of scope).
|
||||
let (kr, kb) = match (*frame).colorspace {
|
||||
ff::AVColorSpace::AVCOL_SPC_BT709 => (0.2126, 0.0722),
|
||||
ff::AVColorSpace::AVCOL_SPC_BT470BG | ff::AVColorSpace::AVCOL_SPC_SMPTE170M => {
|
||||
(0.299, 0.114)
|
||||
}
|
||||
ff::AVColorSpace::AVCOL_SPC_SMPTE240M => (0.212, 0.087),
|
||||
ff::AVColorSpace::AVCOL_SPC_BT2020_NCL | ff::AVColorSpace::AVCOL_SPC_BT2020_CL => {
|
||||
(0.2627, 0.0593)
|
||||
}
|
||||
_ => {
|
||||
if height <= 576 {
|
||||
(0.299, 0.114) // SD → BT.601
|
||||
} else {
|
||||
(0.2126, 0.0722) // HD/UHD → BT.709
|
||||
}
|
||||
}
|
||||
};
|
||||
let coeffs = ycbcr_coeffs(kr, kb);
|
||||
|
||||
if std::env::var("LB_VIDEO_DEBUG").is_ok()
|
||||
&& !self.logged.swap(true, std::sync::atomic::Ordering::Relaxed)
|
||||
{
|
||||
eprintln!(
|
||||
"[hw_video] {}x{} ten_bit={} full_range={} colorspace={:?} primaries={:?} trc={:?}",
|
||||
width, height, ten_bit, full_range,
|
||||
(*frame).colorspace, (*frame).color_primaries, (*frame).color_trc,
|
||||
);
|
||||
}
|
||||
|
||||
// Transfer characteristic → which EOTF the compositor applies to reach scene-linear.
|
||||
let transfer = match (*frame).color_trc {
|
||||
ff::AVColorTransferCharacteristic::AVCOL_TRC_SMPTE2084 => VideoTransfer::Pq,
|
||||
ff::AVColorTransferCharacteristic::AVCOL_TRC_ARIB_STD_B67 => VideoTransfer::Hlg,
|
||||
_ => VideoTransfer::Gamma,
|
||||
};
|
||||
// Primaries → BT.2020 is gamut-mapped to BT.709; unspecified follows the matrix guess above.
|
||||
let primaries = match (*frame).color_primaries {
|
||||
ff::AVColorPrimaries::AVCOL_PRI_BT2020 => VideoPrimaries::Bt2020,
|
||||
ff::AVColorPrimaries::AVCOL_PRI_UNSPECIFIED
|
||||
if matches!(
|
||||
(*frame).colorspace,
|
||||
ff::AVColorSpace::AVCOL_SPC_BT2020_NCL | ff::AVColorSpace::AVCOL_SPC_BT2020_CL
|
||||
) =>
|
||||
{
|
||||
VideoPrimaries::Bt2020
|
||||
}
|
||||
_ => VideoPrimaries::Bt709,
|
||||
};
|
||||
|
||||
let imported = dmabuf::import_raw(&self.device, &self.adapter, &buf);
|
||||
ff::av_frame_free(&mut (drm_f as *mut _)); // the fd was dup'd into Vulkan
|
||||
let (y, uv) = match imported {
|
||||
Ok(t) => t.into_planes(),
|
||||
Err(e) => {
|
||||
// Surface the failure: a silent None here makes core fall back to software (no gamut
|
||||
// conversion → BT.2020 looks washed out). 10-bit P010 import is the likely culprit.
|
||||
eprintln!("[hw_video] import_raw failed (ten_bit={ten_bit}): {e}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
Some(GpuVideoFrame {
|
||||
y: Arc::new(y),
|
||||
uv: Arc::new(uv),
|
||||
width,
|
||||
height,
|
||||
full_range,
|
||||
coeffs,
|
||||
transfer,
|
||||
primaries,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Create the VAAPI hardware device and install hardware decode into `vm`, importing onto the
|
||||
/// shared `device`/`adapter`. Logs and no-ops if VAAPI is unavailable (→ software decode).
|
||||
pub fn install(vm: &Arc<Mutex<VideoManager>>, device: &wgpu::Device, adapter: &wgpu::Adapter) {
|
||||
match gpu_video_encoder::vaapi::create_device() {
|
||||
Ok(hw_device) => {
|
||||
let importer = Arc::new(SharedHwImporter {
|
||||
device: device.clone(),
|
||||
adapter: adapter.clone(),
|
||||
logged: std::sync::atomic::AtomicBool::new(false),
|
||||
});
|
||||
if let Ok(mut vm) = vm.lock() {
|
||||
vm.set_hardware_decode(
|
||||
HwDeviceHandle(hw_device as *mut std::ffi::c_void),
|
||||
importer,
|
||||
);
|
||||
}
|
||||
println!("🎞 Hardware video decode enabled (VAAPI → shared device)");
|
||||
}
|
||||
Err(e) => {
|
||||
println!("🎞 Hardware video decode unavailable ({e}); using software decode");
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,83 @@
|
||||
//! Lucide icon font (ISC license — see `assets/fonts/LICENSE-lucide.txt`).
|
||||
#![allow(dead_code)] // a forward-looking icon palette; not all are wired up yet
|
||||
//!
|
||||
//! The font is embedded and registered as a named egui font family ("lucide"). Icons are drawn as
|
||||
//! text using [`font`] for the `FontId`, with the codepoint constants below (Lucide's private-use
|
||||
//! area). Run [`install`] once at startup.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
/// The egui font-family name the Lucide glyphs live under.
|
||||
pub const FAMILY: &str = "lucide";
|
||||
|
||||
/// Embed + register the Lucide icon font. Call once with the egui context at startup.
|
||||
pub fn install(ctx: &egui::Context) {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
fonts.font_data.insert(
|
||||
"lucide".to_owned(),
|
||||
Arc::new(egui::FontData::from_static(include_bytes!(
|
||||
"../../assets/fonts/lucide.ttf"
|
||||
))),
|
||||
);
|
||||
fonts
|
||||
.families
|
||||
.insert(egui::FontFamily::Name(FAMILY.into()), vec!["lucide".to_owned()]);
|
||||
ctx.set_fonts(fonts);
|
||||
}
|
||||
|
||||
/// A `FontId` in the Lucide family at `size`.
|
||||
pub fn font(size: f32) -> egui::FontId {
|
||||
egui::FontId::new(size, egui::FontFamily::Name(FAMILY.into()))
|
||||
}
|
||||
|
||||
// --- Codepoints (Lucide PUA). Add more as the mobile UI needs them. ---
|
||||
pub const MAXIMIZE: &str = "\u{e112}";
|
||||
pub const MINIMIZE: &str = "\u{e11a}";
|
||||
pub const ARROW_LEFT_RIGHT: &str = "\u{e24a}";
|
||||
pub const ARROW_RIGHT_FROM_LINE: &str = "\u{e458}"; // output port
|
||||
pub const ARROW_RIGHT_TO_LINE: &str = "\u{e459}"; // input port
|
||||
pub const GRIP_HORIZONTAL: &str = "\u{e0ea}";
|
||||
pub const CHEVRONS_UP: &str = "\u{e074}";
|
||||
pub const PLAY: &str = "\u{e13c}";
|
||||
pub const PAUSE: &str = "\u{e12e}";
|
||||
pub const SETTINGS: &str = "\u{e154}";
|
||||
pub const SEARCH: &str = "\u{e151}";
|
||||
pub const PLUS: &str = "\u{e13d}";
|
||||
pub const X: &str = "\u{e1b2}";
|
||||
pub const MENU: &str = "\u{e115}";
|
||||
// Intent-picker icons.
|
||||
pub const BRUSH: &str = "\u{e1d3}";
|
||||
pub const FILM: &str = "\u{e0d0}";
|
||||
pub const MUSIC: &str = "\u{e122}";
|
||||
pub const MIC: &str = "\u{e118}";
|
||||
pub const CLAPPERBOARD: &str = "\u{e29b}";
|
||||
pub const SQUARE_DASHED: &str = "\u{e1cb}";
|
||||
pub const FOLDER_OPEN: &str = "\u{e247}";
|
||||
// Tool icons (omnibutton).
|
||||
pub const MOUSE_POINTER_2: &str = "\u{e1c3}";
|
||||
pub const PENCIL: &str = "\u{e1f9}";
|
||||
pub const MOVE: &str = "\u{e121}";
|
||||
pub const VECTOR_SQUARE: &str = "\u{e67c}";
|
||||
pub const SQUARE: &str = "\u{e167}";
|
||||
pub const CIRCLE: &str = "\u{e076}";
|
||||
pub const MINUS: &str = "\u{e11c}";
|
||||
pub const HEXAGON: &str = "\u{e0f3}";
|
||||
pub const PAINT_BUCKET: &str = "\u{e2e6}";
|
||||
pub const PIPETTE: &str = "\u{e13b}";
|
||||
pub const TYPE: &str = "\u{e198}";
|
||||
pub const ERASER: &str = "\u{e28f}";
|
||||
pub const PEN_TOOL: &str = "\u{e131}";
|
||||
pub const BLEND: &str = "\u{e59c}";
|
||||
pub const WAND_SPARKLES: &str = "\u{e357}";
|
||||
pub const LASSO_SELECT: &str = "\u{e1cf}";
|
||||
pub const SCISSORS: &str = "\u{e14e}";
|
||||
// Create-menu icons.
|
||||
pub const AUDIO_WAVEFORM: &str = "\u{e55b}";
|
||||
pub const PIANO: &str = "\u{e561}";
|
||||
pub const FOLDER: &str = "\u{e0d7}";
|
||||
pub const FILE_PLUS: &str = "\u{e0c9}";
|
||||
pub const COPY: &str = "\u{e09e}";
|
||||
pub const LAYERS: &str = "\u{e529}";
|
||||
pub const ELLIPSIS: &str = "\u{e0b6}";
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Selection inspector bottom sheet. When something is selected/focused it rises above the
|
||||
//! transport, showing the focused object's properties by reusing `InfopanelPane` full-bleed.
|
||||
//! Jump-to chips slide the stack window to the related surface; the ✕ deselects.
|
||||
|
||||
use eframe::egui;
|
||||
use lightningbeam_core::pane::PaneType;
|
||||
use lightningbeam_core::selection::FocusSelection;
|
||||
|
||||
use super::{surface, MobileState, Palette, MOBILE_NS};
|
||||
use crate::panes::{NodePath, SharedPaneState};
|
||||
use crate::RenderContext;
|
||||
|
||||
const GRAB_H: f32 = 16.0;
|
||||
const HEAD_H: f32 = 44.0;
|
||||
|
||||
fn inspector_path() -> NodePath {
|
||||
vec![MOBILE_NS, 200]
|
||||
}
|
||||
|
||||
/// Whether anything is selected/focused (i.e. the inspector should be shown).
|
||||
pub fn is_active(shared: &SharedPaneState) -> bool {
|
||||
!shared.focus.is_none() || !shared.selection.is_empty()
|
||||
}
|
||||
|
||||
/// A cheap content-sensitive signature of the current selection, so the shell can detect when the
|
||||
/// selection *changes* (to re-show a manually-dismissed inspector for the new thing).
|
||||
pub fn selection_sig(shared: &SharedPaneState) -> u64 {
|
||||
let mut h: u64 = 0;
|
||||
for id in shared.selection.clip_instances() {
|
||||
h ^= (id.as_u128() as u64).wrapping_mul(0x9E3779B97F4A7C15);
|
||||
}
|
||||
for f in shared.selection.selected_fills() {
|
||||
h ^= (f.idx() as u64).wrapping_mul(0xD1B54A32D192ED03);
|
||||
}
|
||||
for e in shared.selection.selected_edges() {
|
||||
h ^= (e.idx() as u64).wrapping_mul(0xA24BAED4963EE407);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// The stack slot (see `super::STACK`) where the current selection lives, so we can tell if the
|
||||
/// sheet would cover it. Geometry/selection lives on the Stage; clips/layers on the Timeline; etc.
|
||||
#[allow(dead_code)] // selection→pane mapping; kept for reflow/jump heuristics
|
||||
pub fn target_slot(shared: &SharedPaneState) -> usize {
|
||||
match &*shared.focus {
|
||||
FocusSelection::Notes { .. } => 4, // PianoRoll
|
||||
FocusSelection::Nodes(_) => 5, // Node/Instrument
|
||||
FocusSelection::Assets(_) => 1, // Asset Library
|
||||
FocusSelection::ClipInstances(_) | FocusSelection::Layers(_) => 3, // Timeline
|
||||
FocusSelection::Geometry { .. } | FocusSelection::None => 2, // Stage
|
||||
}
|
||||
}
|
||||
|
||||
/// A short title describing what's selected.
|
||||
fn title(shared: &SharedPaneState) -> String {
|
||||
use lightningbeam_core::layer::{AnyLayer, AudioLayerType};
|
||||
let plural = |n: usize, s: &str| {
|
||||
if n == 1 {
|
||||
format!("1 {s}")
|
||||
} else {
|
||||
format!("{n} {s}s")
|
||||
}
|
||||
};
|
||||
match &*shared.focus {
|
||||
FocusSelection::Layers(ids) => {
|
||||
let doc = shared.action_executor.document();
|
||||
match ids.len() {
|
||||
0 => "Layer".to_string(),
|
||||
1 => {
|
||||
if let Some(l) = doc.get_layer(&ids[0]) {
|
||||
let ty = match l {
|
||||
AnyLayer::Vector(_) => "Vector",
|
||||
AnyLayer::Audio(a) => match a.audio_layer_type {
|
||||
AudioLayerType::Midi => "MIDI",
|
||||
AudioLayerType::Sampled => "Audio",
|
||||
},
|
||||
AnyLayer::Video(_) => "Video",
|
||||
AnyLayer::Effect(_) => "Effect",
|
||||
AnyLayer::Group(_) => "Group",
|
||||
AnyLayer::Raster(_) => "Raster",
|
||||
AnyLayer::Text(_) => "Text",
|
||||
};
|
||||
format!("{} · {} layer", l.name(), ty)
|
||||
} else {
|
||||
"Layer".to_string()
|
||||
}
|
||||
}
|
||||
n => plural(n, "layer"),
|
||||
}
|
||||
}
|
||||
FocusSelection::ClipInstances(ids) => plural(ids.len(), "clip"),
|
||||
FocusSelection::Notes { indices, .. } => plural(indices.len().max(1), "note"),
|
||||
FocusSelection::Nodes(ids) => plural(ids.len(), "node"),
|
||||
FocusSelection::Assets(ids) => plural(ids.len(), "asset"),
|
||||
FocusSelection::Geometry { .. } | FocusSelection::None => "Selection".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A jump-to chip: its label and the stack window it brings into view (top, count). These reframe
|
||||
/// to a related surface with the object still selected.
|
||||
struct Chip {
|
||||
label: &'static str,
|
||||
window: (usize, usize),
|
||||
}
|
||||
|
||||
const CHIPS: [Chip; 2] = [
|
||||
Chip { label: "Timeline", window: (3, 1) }, // Timeline = STACK index 3
|
||||
Chip { label: "Nodes", window: (5, 1) }, // Node/Instrument = STACK index 5
|
||||
];
|
||||
|
||||
pub fn render(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
region: egui::Rect,
|
||||
rc: &mut RenderContext,
|
||||
state: &mut MobileState,
|
||||
pal: &Palette,
|
||||
landscape: bool,
|
||||
) {
|
||||
// Panel background + border, with rounded corners on the edge that faces the content (top in
|
||||
// portrait, left in landscape).
|
||||
let radius = if landscape {
|
||||
egui::CornerRadius { nw: 14, ne: 0, sw: 14, se: 0 }
|
||||
} else {
|
||||
egui::CornerRadius { nw: 14, ne: 14, sw: 0, se: 0 }
|
||||
};
|
||||
ui.painter().rect_filled(rect, radius, pal.surface_alt);
|
||||
ui.painter().rect_stroke(rect, radius, egui::Stroke::new(1.0, pal.line), egui::StrokeKind::Inside);
|
||||
|
||||
// Grab handle — top strip (portrait, drags height) or left strip (landscape, drags width).
|
||||
// `content_area` is the panel minus the grab strip.
|
||||
let content_area = if landscape {
|
||||
let grab = egui::Rect::from_min_max(rect.left_top(), egui::pos2(rect.left() + GRAB_H, rect.bottom()));
|
||||
let gresp = ui.interact(grab, ui.id().with("mobile_inspector_grab"), egui::Sense::drag());
|
||||
let pill = egui::Rect::from_center_size(grab.center(), egui::vec2(4.0, 34.0));
|
||||
ui.painter().rect_filled(pill, 2.0, if gresp.hovered() || gresp.dragged() { pal.accent } else { pal.line });
|
||||
if gresp.dragged() && region.width() > 1.0 {
|
||||
state.inspector_width_frac = (state.inspector_width_frac - gresp.drag_delta().x / region.width()).clamp(0.2, 0.7);
|
||||
}
|
||||
if gresp.hovered() || gresp.dragged() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
|
||||
}
|
||||
egui::Rect::from_min_max(egui::pos2(grab.right(), rect.top()), rect.max)
|
||||
} else {
|
||||
let grab = egui::Rect::from_min_max(rect.left_top(), egui::pos2(rect.right(), rect.top() + GRAB_H));
|
||||
let gresp = ui.interact(grab, ui.id().with("mobile_inspector_grab"), egui::Sense::drag());
|
||||
let pill = egui::Rect::from_center_size(grab.center(), egui::vec2(34.0, 4.0));
|
||||
ui.painter().rect_filled(pill, 2.0, if gresp.hovered() || gresp.dragged() { pal.accent } else { pal.line });
|
||||
if gresp.dragged() && region.height() > 1.0 {
|
||||
state.inspector_frac = (state.inspector_frac - gresp.drag_delta().y / region.height()).clamp(0.2, 0.85);
|
||||
}
|
||||
if gresp.hovered() || gresp.dragged() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
|
||||
}
|
||||
egui::Rect::from_min_max(egui::pos2(rect.left(), grab.bottom()), rect.max)
|
||||
};
|
||||
|
||||
// Single header row (egui widgets — they inherit the mobile touch sizing + theme visuals):
|
||||
// title on the left, [Timeline] [Nodes] jump buttons + ✕ close on the right.
|
||||
let head = egui::Rect::from_min_max(
|
||||
content_area.min,
|
||||
egui::pos2(content_area.right(), content_area.top() + HEAD_H),
|
||||
);
|
||||
let title_text = title(&rc.shared);
|
||||
let mut jump: Option<(usize, usize)> = None;
|
||||
let mut do_close = false;
|
||||
let mut hui = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(head.shrink2(egui::vec2(12.0, 5.0)))
|
||||
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
);
|
||||
hui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui
|
||||
.add(egui::Button::new(egui::RichText::new(super::icons::X).font(super::icons::font(18.0))).frame(false))
|
||||
.clicked()
|
||||
{
|
||||
do_close = true;
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
// Reversed so the visual order stays Timeline, then Nodes.
|
||||
for chip in CHIPS.iter().rev() {
|
||||
if ui.button(chip.label).clicked() {
|
||||
jump = Some(chip.window);
|
||||
}
|
||||
}
|
||||
// Title fills the remaining space on the left.
|
||||
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
ui.add(egui::Label::new(egui::RichText::new(title_text).color(pal.text)).truncate());
|
||||
});
|
||||
});
|
||||
if do_close {
|
||||
rc.shared.selection.clear();
|
||||
*rc.shared.focus = FocusSelection::None;
|
||||
}
|
||||
if let Some((top, count)) = jump {
|
||||
state.window_top = top;
|
||||
state.window_count = count;
|
||||
state.weights = [1.0, 1.0, 1.0];
|
||||
state.anim = None;
|
||||
}
|
||||
|
||||
// Properties content — reuse the Infopanel full-bleed.
|
||||
let content = egui::Rect::from_min_max(
|
||||
egui::pos2(content_area.left(), head.bottom()),
|
||||
content_area.max,
|
||||
);
|
||||
if content.height() > 1.0 {
|
||||
surface::render_surface_fullbleed(ui, content, &inspector_path(), PaneType::Infopanel, rc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Mobile new-file intent picker — the phone equivalent of the desktop start screen.
|
||||
//!
|
||||
//! Mirrors the desktop "new project" flow: each intent calls
|
||||
//! [`EditorApp::create_new_project_with_focus`] (which builds the document, picks a default layer,
|
||||
//! and switches to editor mode) and then sets the initial mobile stack window so the relevant panes
|
||||
//! are in view.
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
use super::{icons, Palette};
|
||||
use crate::EditorApp;
|
||||
|
||||
/// One intent card.
|
||||
struct Intent {
|
||||
label: &'static str,
|
||||
icon: &'static str,
|
||||
accent: egui::Color32,
|
||||
/// Argument to `create_new_project_with_focus` (0=Animation, 1=Video, 2=Music, 5=Painting).
|
||||
focus: usize,
|
||||
/// Initial mobile stack window: (window_top, window_count).
|
||||
window: (usize, usize),
|
||||
/// Initial pane weights (relative heights) for the window.
|
||||
weights: [f32; 3],
|
||||
}
|
||||
|
||||
fn intents(pal: &Palette) -> [Intent; 6] {
|
||||
let [coral, cyan, amber, pink, violet] = pal.accents;
|
||||
let even = [1.0, 1.0, 1.0];
|
||||
// Compose/Record: compressed Timeline ribbon on top; the tall Piano Roll (which now hosts the
|
||||
// instrument header + keyboard as one surface) fills the rest.
|
||||
let music = [0.4, 1.6, 1.0];
|
||||
[
|
||||
// Stage indices (see super::STACK): Stage=2, Timeline=3, PianoRoll=4, VirtualPiano=5.
|
||||
Intent { label: "Draw", icon: icons::BRUSH, accent: coral, focus: 5, window: (2, 1), weights: even },
|
||||
Intent { label: "Animate", icon: icons::FILM, accent: cyan, focus: 0, window: (2, 2), weights: even },
|
||||
Intent { label: "Compose", icon: icons::MUSIC, accent: amber, focus: 2, window: (3, 2), weights: music },
|
||||
Intent { label: "Record", icon: icons::MIC, accent: pink, focus: 2, window: (3, 2), weights: music },
|
||||
Intent { label: "Edit video", icon: icons::CLAPPERBOARD, accent: violet, focus: 1, window: (2, 2), weights: even },
|
||||
Intent { label: "Blank", icon: icons::SQUARE_DASHED, accent: pal.text_dim, focus: 0, window: (2, 2), weights: even },
|
||||
]
|
||||
}
|
||||
|
||||
pub fn render(app: &mut EditorApp, ctx: &egui::Context) {
|
||||
let pal = Palette::from_theme(&app.theme, ctx);
|
||||
egui::CentralPanel::default()
|
||||
.frame(egui::Frame::NONE.fill(pal.bg))
|
||||
.show(ctx, |ui| {
|
||||
let rect = ui.available_rect_before_wrap();
|
||||
let margin = 16.0;
|
||||
let left = rect.left() + margin;
|
||||
let right = rect.right() - margin;
|
||||
|
||||
// Header.
|
||||
ui.painter().text(
|
||||
egui::pos2(left, rect.top() + 22.0),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"Start something",
|
||||
egui::FontId::proportional(22.0),
|
||||
pal.text,
|
||||
);
|
||||
|
||||
let landscape = rect.width() > rect.height();
|
||||
let content_top = rect.top() + 62.0;
|
||||
let content_bottom = rect.bottom() - margin;
|
||||
let gap = 10.0;
|
||||
|
||||
// Portrait: 3 rows × 2 cols of intent cards up top, recent list below.
|
||||
// Landscape: 2 rows × 3 cols on the left, recent list to the right.
|
||||
let (cols, rows) = if landscape { (3usize, 2usize) } else { (2usize, 3usize) };
|
||||
let (grid_rect, recent_rect) = if landscape {
|
||||
let split = left + (right - left) * 0.62;
|
||||
(
|
||||
egui::Rect::from_min_max(egui::pos2(left, content_top), egui::pos2(split - gap, content_bottom)),
|
||||
egui::Rect::from_min_max(egui::pos2(split + gap, content_top), egui::pos2(right, content_bottom)),
|
||||
)
|
||||
} else {
|
||||
let grid_h = (content_bottom - content_top) * 0.66;
|
||||
(
|
||||
egui::Rect::from_min_max(egui::pos2(left, content_top), egui::pos2(right, content_top + grid_h)),
|
||||
egui::Rect::from_min_max(egui::pos2(left, content_top + grid_h + 14.0), egui::pos2(right, content_bottom)),
|
||||
)
|
||||
};
|
||||
|
||||
// Floor at 0 so a very small window can't produce negative/inverted card rects.
|
||||
let col_w = ((grid_rect.width() - (cols as f32 - 1.0) * gap) / cols as f32).max(0.0);
|
||||
let card_h = ((grid_rect.height() - (rows as f32 - 1.0) * gap) / rows as f32).max(0.0);
|
||||
for (i, intent) in intents(&pal).iter().enumerate() {
|
||||
let col = (i % cols) as f32;
|
||||
let row = (i / cols) as f32;
|
||||
let cx = grid_rect.left() + col * (col_w + gap);
|
||||
let cy = grid_rect.top() + row * (card_h + gap);
|
||||
let card = egui::Rect::from_min_size(egui::pos2(cx, cy), egui::vec2(col_w, card_h));
|
||||
|
||||
let resp = ui.interact(card, ui.id().with(("mobile_intent", i)), egui::Sense::click());
|
||||
let p = ui.painter();
|
||||
p.rect_filled(card, 12.0, if resp.hovered() { pal.surface_alt } else { pal.surface });
|
||||
p.rect_stroke(card, 12.0, egui::Stroke::new(1.0, pal.line), egui::StrokeKind::Inside);
|
||||
p.text(
|
||||
egui::pos2(card.center().x, card.top() + card.height() * 0.40),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
intent.icon,
|
||||
icons::font(30.0),
|
||||
intent.accent,
|
||||
);
|
||||
p.text(
|
||||
egui::pos2(card.center().x, card.bottom() - 18.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
intent.label,
|
||||
egui::FontId::proportional(15.0),
|
||||
pal.text,
|
||||
);
|
||||
|
||||
if resp.clicked() {
|
||||
app.create_new_project_with_focus(intent.focus);
|
||||
app.mobile_state.window_top = intent.window.0;
|
||||
app.mobile_state.window_count = intent.window.1;
|
||||
app.mobile_state.weights = intent.weights;
|
||||
}
|
||||
}
|
||||
|
||||
// Recent projects list (below the grid in portrait, beside it in landscape).
|
||||
let rleft = recent_rect.left();
|
||||
let rright = recent_rect.right();
|
||||
ui.painter().text(
|
||||
egui::pos2(rleft, recent_rect.top()),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"Recent",
|
||||
egui::FontId::proportional(13.0),
|
||||
pal.text_dim,
|
||||
);
|
||||
let list_top = recent_rect.top() + 22.0;
|
||||
let recents = app.config.get_recent_files();
|
||||
if recents.is_empty() {
|
||||
ui.painter().text(
|
||||
egui::pos2(rleft, list_top + 8.0),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"No recent projects",
|
||||
egui::FontId::proportional(12.0),
|
||||
pal.text_dim,
|
||||
);
|
||||
} else {
|
||||
let row_h = 38.0;
|
||||
let row_gap = 6.0;
|
||||
let avail = recent_rect.bottom() - list_top;
|
||||
let max_rows = ((avail + row_gap) / (row_h + row_gap)).floor().max(0.0) as usize;
|
||||
let mut chosen: Option<std::path::PathBuf> = None;
|
||||
for (j, path) in recents.iter().take(max_rows).enumerate() {
|
||||
let ry = list_top + j as f32 * (row_h + row_gap);
|
||||
let row_rect =
|
||||
egui::Rect::from_min_max(egui::pos2(rleft, ry), egui::pos2(rright, ry + row_h));
|
||||
let resp =
|
||||
ui.interact(row_rect, ui.id().with(("mobile_recent", j)), egui::Sense::click());
|
||||
let p = ui.painter();
|
||||
p.rect_filled(row_rect, 8.0, if resp.hovered() { pal.surface_alt } else { pal.surface });
|
||||
p.rect_stroke(row_rect, 8.0, egui::Stroke::new(1.0, pal.line), egui::StrokeKind::Inside);
|
||||
p.text(
|
||||
egui::pos2(row_rect.left() + 12.0, row_rect.center().y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
icons::FOLDER_OPEN,
|
||||
icons::font(15.0),
|
||||
pal.text_dim,
|
||||
);
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "Untitled".to_string());
|
||||
p.text(
|
||||
egui::pos2(row_rect.left() + 36.0, row_rect.center().y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
&name,
|
||||
egui::FontId::proportional(13.0),
|
||||
pal.text,
|
||||
);
|
||||
if resp.clicked() {
|
||||
chosen = Some(path.clone());
|
||||
}
|
||||
}
|
||||
if let Some(path) = chosen {
|
||||
app.load_from_file(path);
|
||||
app.app_mode = crate::AppMode::Editor;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
//! Mobile / phone UI shell.
|
||||
//!
|
||||
//! Developed on desktop behind the `LB_MOBILE_UI` env var (see [`is_mobile_env`]).
|
||||
//!
|
||||
//! The shell is a single **vertical sliding-window stack** of the existing panes: a fixed
|
||||
//! top→bottom order, with a window of 2 or 3 consecutive panes visible at once. Dragging the
|
||||
//! dividers between panes and the top/bottom screen edges grows, shrinks, or slides the window
|
||||
//! (the R1–R6 state machine in `stack.rs`). A transport bar is pinned at the bottom as the floor.
|
||||
//!
|
||||
//! Each visible pane reuses the existing `PaneInstance::render_content` full-bleed (see
|
||||
//! `surface.rs`). Per the wireframe, the Toolbar becomes the omnibutton and the Infopanel becomes
|
||||
//! the selection inspector (later phases), so neither is in the stack.
|
||||
|
||||
use eframe::egui;
|
||||
use lightningbeam_core::pane::PaneType;
|
||||
|
||||
use crate::panes::NodePath;
|
||||
use crate::RenderContext;
|
||||
|
||||
pub mod icons;
|
||||
mod inspector;
|
||||
pub mod intent;
|
||||
mod omni;
|
||||
mod palette;
|
||||
mod stack;
|
||||
mod surface;
|
||||
mod topbar;
|
||||
mod transport;
|
||||
|
||||
use palette::Palette;
|
||||
|
||||
/// Reserved sentinel namespace for mobile pane-instance paths. Desktop layout paths are built
|
||||
/// from small child indices, so prefixing with `usize::MAX` guarantees mobile slots never alias a
|
||||
/// real layout path in the shared `pane_instances` map.
|
||||
pub const MOBILE_NS: usize = usize::MAX;
|
||||
|
||||
const TRANSPORT_H: f32 = 60.0;
|
||||
const TOPBAR_H: f32 = 40.0;
|
||||
|
||||
/// Clamp a desktop dialog width to fit the current screen (with side margins). A no-op on wide
|
||||
/// desktop screens (`min` keeps the desired width); on a phone-aspect window it shrinks to fit.
|
||||
pub fn dialog_width(ctx: &egui::Context, desired: f32) -> f32 {
|
||||
let avail = ctx.screen_rect().width() - 24.0;
|
||||
desired.min(avail.max(200.0))
|
||||
}
|
||||
|
||||
/// Enlarge egui's spacing/sizing so the standard widgets (buttons, dropdowns, sliders, text fields)
|
||||
/// in panes and dialogs are touch-friendly. Applied every frame after the theme visuals when the
|
||||
/// mobile shell is active. The mobile chrome (transport, omnibutton, headers) is hand-sized already;
|
||||
/// this targets the egui-widget content inside panes.
|
||||
pub fn apply_touch_style(ctx: &egui::Context) {
|
||||
use egui::{FontId, TextStyle};
|
||||
ctx.style_mut(|s| {
|
||||
let sp = &mut s.spacing;
|
||||
// Minimum touch target height for buttons/sliders/checkboxes.
|
||||
sp.interact_size = egui::vec2(sp.interact_size.x.max(44.0), 38.0);
|
||||
sp.button_padding = egui::vec2(12.0, 9.0);
|
||||
sp.item_spacing = egui::vec2(10.0, 10.0);
|
||||
sp.slider_width = 200.0;
|
||||
sp.slider_rail_height = 10.0;
|
||||
sp.combo_width = 200.0;
|
||||
sp.combo_height = 360.0;
|
||||
sp.text_edit_width = 220.0;
|
||||
sp.icon_width = 24.0;
|
||||
sp.icon_width_inner = 14.0;
|
||||
sp.icon_spacing = 8.0;
|
||||
sp.scroll.bar_width = 16.0;
|
||||
sp.menu_margin = egui::Margin::same(8);
|
||||
// Larger text for touch legibility.
|
||||
s.text_styles.insert(TextStyle::Body, FontId::proportional(15.0));
|
||||
s.text_styles.insert(TextStyle::Button, FontId::proportional(15.0));
|
||||
s.text_styles.insert(TextStyle::Monospace, FontId::monospace(13.0));
|
||||
s.text_styles.insert(TextStyle::Small, FontId::proportional(12.0));
|
||||
});
|
||||
}
|
||||
|
||||
/// Returns true if the mobile UI is requested via the `LB_MOBILE_UI` env var.
|
||||
/// Any non-empty value other than "0" enables it.
|
||||
pub fn is_mobile_env() -> bool {
|
||||
std::env::var("LB_MOBILE_UI")
|
||||
.map(|v| !v.is_empty() && v != "0")
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// `LB_MOBILE_UI=2` develops the mobile shell in landscape (opens a landscape phone window).
|
||||
/// Orientation itself is aspect-based at render time; this only picks the initial window aspect.
|
||||
pub fn is_mobile_landscape_env() -> bool {
|
||||
std::env::var("LB_MOBILE_UI").map(|v| v == "2").unwrap_or(false)
|
||||
}
|
||||
|
||||
/// The panes that make up the vertical stack, in fixed top→bottom order.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum StackPane {
|
||||
Outliner,
|
||||
AssetLibrary,
|
||||
Stage,
|
||||
Timeline,
|
||||
/// The instrument surface: keyboard-primary on mobile, hosting the falling-notes roll above the
|
||||
/// keys (the standalone Virtual Piano is embedded here, so it isn't a separate stack slot).
|
||||
PianoRoll,
|
||||
/// Node editor, or (toggled) the instrument/preset browser.
|
||||
NodeInstrument,
|
||||
ScriptEditor,
|
||||
}
|
||||
|
||||
/// The stack order. Index into this is a pane's stable slot id.
|
||||
pub const STACK: [StackPane; 7] = [
|
||||
StackPane::Outliner,
|
||||
StackPane::AssetLibrary,
|
||||
StackPane::Stage,
|
||||
StackPane::Timeline,
|
||||
StackPane::PianoRoll,
|
||||
StackPane::NodeInstrument,
|
||||
StackPane::ScriptEditor,
|
||||
];
|
||||
|
||||
impl StackPane {
|
||||
/// The backing pane type. The Node/Instrument slot picks NodeEditor or PresetBrowser based on
|
||||
/// the toggle.
|
||||
pub fn pane_type(self, show_instruments: bool) -> PaneType {
|
||||
match self {
|
||||
StackPane::Outliner => PaneType::Outliner,
|
||||
StackPane::AssetLibrary => PaneType::AssetLibrary,
|
||||
StackPane::Stage => PaneType::Stage,
|
||||
StackPane::Timeline => PaneType::Timeline,
|
||||
StackPane::PianoRoll => PaneType::PianoRoll,
|
||||
StackPane::NodeInstrument => {
|
||||
if show_instruments {
|
||||
PaneType::PresetBrowser
|
||||
} else {
|
||||
PaneType::NodeEditor
|
||||
}
|
||||
}
|
||||
StackPane::ScriptEditor => PaneType::ScriptEditor,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self, show_instruments: bool) -> &'static str {
|
||||
match self {
|
||||
StackPane::Outliner => "Outliner",
|
||||
StackPane::AssetLibrary => "Assets",
|
||||
StackPane::Stage => "Stage",
|
||||
StackPane::Timeline => "Timeline",
|
||||
StackPane::PianoRoll => "Instrument",
|
||||
StackPane::NodeInstrument => {
|
||||
if show_instruments {
|
||||
"Instruments"
|
||||
} else {
|
||||
"Nodes"
|
||||
}
|
||||
}
|
||||
StackPane::ScriptEditor => "Script",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `pane_instances` key for a stack slot.
|
||||
fn slot_path(slot: usize) -> NodePath {
|
||||
vec![MOBILE_NS, slot]
|
||||
}
|
||||
|
||||
/// An in-progress drag of a stack handle.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct StackDrag {
|
||||
pub handle: stack::Handle,
|
||||
/// Accumulated pointer offset (px) since the drag began (downward positive).
|
||||
pub offset: f32,
|
||||
}
|
||||
|
||||
/// A short ease between two stack layouts (resize snap, membership change, or fullscreen toggle).
|
||||
/// Both endpoints are full configs so the same animation covers panes resizing AND panes
|
||||
/// entering/leaving the window.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct LayoutAnim {
|
||||
pub from_top: usize,
|
||||
pub from_count: usize,
|
||||
pub from_w: [f32; 3],
|
||||
pub to_top: usize,
|
||||
pub to_count: usize,
|
||||
pub to_w: [f32; 3],
|
||||
/// egui time (seconds) when the animation started (may be back-dated to continue a drag).
|
||||
pub start: f64,
|
||||
}
|
||||
|
||||
/// Persistent mobile-shell state, cached on `EditorApp`.
|
||||
pub struct MobileState {
|
||||
/// Index into `STACK` of the topmost visible pane.
|
||||
pub window_top: usize,
|
||||
/// Number of visible panes (1, 2, or 3; 1 = a single pane filling the stack).
|
||||
pub window_count: usize,
|
||||
/// Relative heights of the visible panes (first `window_count` entries are used; normalized on
|
||||
/// use). Reset to even on any membership change; adjusted by intermediate divider snapping.
|
||||
pub weights: [f32; 3],
|
||||
/// Node/Instrument band: false = node editor, true = instrument/preset browser.
|
||||
pub show_instruments: bool,
|
||||
/// Inspector sheet height as a fraction of the region above the transport (portrait).
|
||||
pub inspector_frac: f32,
|
||||
/// Inspector side-panel width as a fraction of the region (landscape).
|
||||
pub inspector_width_frac: f32,
|
||||
/// Last frame's orientation (landscape?), to reset orientation-specific cached state on rotation.
|
||||
pub was_landscape: bool,
|
||||
/// Whether the inspector sheet is currently shown. Gated to appear on pointer *release* (a tap),
|
||||
/// not on press, so press+drag interactions aren't interrupted by the sheet popping up.
|
||||
pub inspector_visible: bool,
|
||||
/// Screen-y of the tap that opened the inspector — used to decide whether the tapped thing would
|
||||
/// be hidden by the sheet (only then do we reflow the stack).
|
||||
pub inspector_anchor_y: f32,
|
||||
/// Set when the user taps outside the sheet to dismiss it; suppresses re-showing until the
|
||||
/// selection changes. Reset when the selection signature below changes.
|
||||
pub inspector_dismissed: bool,
|
||||
/// Cheap signature of the current selection, to detect when it changes (re-show the inspector).
|
||||
pub inspector_sel_sig: u64,
|
||||
/// Whether the omnibutton radial tool menu is open.
|
||||
pub omni_open: bool,
|
||||
/// Whether the omnibutton "more" grid (all tools) is open.
|
||||
pub omni_grid_open: bool,
|
||||
/// Whether the omnibutton "+New" create grid is open.
|
||||
pub omni_create_open: bool,
|
||||
/// Top-bar overflow (⋯ commands) sheet open.
|
||||
pub overflow_open: bool,
|
||||
/// Top-bar command palette (⌕) open, and its search query.
|
||||
pub palette_open: bool,
|
||||
pub palette_query: String,
|
||||
/// Active handle drag (transient).
|
||||
pub drag: Option<StackDrag>,
|
||||
/// In-flight layout ease (transient).
|
||||
pub anim: Option<LayoutAnim>,
|
||||
}
|
||||
|
||||
impl Default for MobileState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
// Launch on {Stage, Timeline}.
|
||||
window_top: 2,
|
||||
window_count: 2,
|
||||
weights: [1.0, 1.0, 1.0],
|
||||
show_instruments: false,
|
||||
inspector_frac: 0.45,
|
||||
inspector_width_frac: 0.4,
|
||||
was_landscape: false,
|
||||
inspector_visible: false,
|
||||
inspector_anchor_y: 0.0,
|
||||
inspector_dismissed: false,
|
||||
inspector_sel_sig: 0,
|
||||
omni_open: false,
|
||||
omni_grid_open: false,
|
||||
omni_create_open: false,
|
||||
overflow_open: false,
|
||||
palette_open: false,
|
||||
palette_query: String::new(),
|
||||
drag: None,
|
||||
anim: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the whole mobile shell into `available_rect`.
|
||||
pub fn render_mobile_shell(
|
||||
ui: &mut egui::Ui,
|
||||
available_rect: egui::Rect,
|
||||
rc: &mut RenderContext,
|
||||
state: &mut MobileState,
|
||||
) {
|
||||
let pal = Palette::from_theme(rc.shared.theme, ui.ctx());
|
||||
|
||||
// Orientation (aspect-based; rotation = a resize). Published to panes before anything renders.
|
||||
let landscape = available_rect.width() > available_rect.height();
|
||||
rc.shared.is_portrait = !landscape;
|
||||
// Rotating while 3 panes are open drops to 2 (landscape caps the stack at 2).
|
||||
if landscape && state.window_count > 2 {
|
||||
state.window_count = 2;
|
||||
state.window_top = state.window_top.min(STACK.len().saturating_sub(2));
|
||||
}
|
||||
// On an orientation change, the cached inspector tap-anchor is in the old layout's coordinate
|
||||
// space; drop it to a non-covering default so the portrait reflow doesn't mis-decide until the
|
||||
// next tap re-anchors.
|
||||
if landscape != state.was_landscape {
|
||||
state.was_landscape = landscape;
|
||||
state.inspector_anchor_y = available_rect.top();
|
||||
}
|
||||
|
||||
// Background (device color; bands paint over most of it).
|
||||
ui.painter().rect_filled(available_rect, 0.0, pal.bg);
|
||||
|
||||
// In landscape the top bar is folded into the top pane header (no separate band), reclaiming its
|
||||
// height for the stack.
|
||||
let topbar_h = if landscape { 0.0 } else { TOPBAR_H };
|
||||
let topbar_rect = egui::Rect::from_min_max(
|
||||
available_rect.min,
|
||||
egui::pos2(available_rect.right(), available_rect.top() + topbar_h),
|
||||
);
|
||||
let transport_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(available_rect.left(), available_rect.bottom() - TRANSPORT_H),
|
||||
available_rect.max,
|
||||
);
|
||||
// Region between the top bar and the transport, shared between the stack and (when something is
|
||||
// selected) the inspector sheet that rises above the transport.
|
||||
let region = egui::Rect::from_min_max(
|
||||
egui::pos2(available_rect.left(), topbar_rect.bottom()),
|
||||
egui::pos2(available_rect.right(), transport_rect.top()),
|
||||
);
|
||||
// The inspector sheet appears on pointer *release* (a tap), not on press — so press+drag on the
|
||||
// canvas isn't interrupted by the sheet popping up. Track visibility: hide when nothing's
|
||||
// selected; show once the pointer is up with a selection; keep it shown while it's being
|
||||
// interacted with (pointer down but still selected).
|
||||
let active = inspector::is_active(&rc.shared);
|
||||
let any_down = ui.input(|i| i.pointer.any_down());
|
||||
let sel_sig = inspector::selection_sig(&rc.shared);
|
||||
if sel_sig != state.inspector_sel_sig {
|
||||
// Selection changed → a fresh thing to inspect; clear any prior manual dismissal.
|
||||
state.inspector_dismissed = false;
|
||||
state.inspector_sel_sig = sel_sig;
|
||||
}
|
||||
if !active {
|
||||
state.inspector_visible = false;
|
||||
state.inspector_dismissed = false;
|
||||
} else if !state.inspector_dismissed && !any_down {
|
||||
if !state.inspector_visible {
|
||||
// Just opened (tap released): anchor to the release position for the reflow test below.
|
||||
state.inspector_anchor_y = ui
|
||||
.input(|i| i.pointer.interact_pos())
|
||||
.map(|p| p.y)
|
||||
.unwrap_or(region.bottom());
|
||||
}
|
||||
state.inspector_visible = true;
|
||||
}
|
||||
let mut inspector_shown = state.inspector_visible;
|
||||
|
||||
// Inspector geometry: a bottom sheet in portrait, a right-side vertical column in landscape.
|
||||
// Clamp defensively: on a very small region the desired minimum can exceed the available space,
|
||||
// and `f32::clamp` panics if `min > max`, so keep `min <= max`.
|
||||
let inspector_rect = if landscape {
|
||||
let lo = 180.0_f32.min(region.width());
|
||||
let hi = (region.width() - 140.0).max(lo);
|
||||
let w = (region.width() * state.inspector_width_frac).clamp(lo, hi);
|
||||
egui::Rect::from_min_max(egui::pos2(region.right() - w, region.top()), region.max)
|
||||
} else {
|
||||
let lo = 120.0_f32.min(region.height());
|
||||
let hi = (region.height() - 60.0).max(lo);
|
||||
let h = (region.height() * state.inspector_frac).clamp(lo, hi);
|
||||
egui::Rect::from_min_max(egui::pos2(region.left(), region.bottom() - h), region.max)
|
||||
};
|
||||
|
||||
// Tapping outside the inspector (but not on the transport) dismisses (hides) it. We only hide —
|
||||
// NOT clear the selection — so actions dispatched from overlays (context menu, "+New" grid) still
|
||||
// see the selection. It stays dismissed until the selection changes (sig above).
|
||||
if inspector_shown {
|
||||
let dismiss = ui.input(|i| {
|
||||
i.pointer.primary_pressed()
|
||||
&& i.pointer.press_origin().map_or(false, |p| {
|
||||
!inspector_rect.contains(p) && !transport_rect.contains(p)
|
||||
})
|
||||
});
|
||||
if dismiss {
|
||||
state.inspector_visible = false;
|
||||
state.inspector_dismissed = true;
|
||||
inspector_shown = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Reflow: shrink the stack to make room for the inspector. Landscape always carves horizontally
|
||||
// (side-by-side); portrait only carves when the tapped thing sits below the sheet (else overlay).
|
||||
// Restoring on dismiss is automatic — reflow only changes the render rect.
|
||||
let stack_rect = if !inspector_shown {
|
||||
region
|
||||
} else if landscape {
|
||||
egui::Rect::from_min_max(region.min, egui::pos2(inspector_rect.left(), region.bottom()))
|
||||
} else if state.inspector_anchor_y > inspector_rect.top() {
|
||||
egui::Rect::from_min_max(region.min, egui::pos2(region.right(), inspector_rect.top()))
|
||||
} else {
|
||||
region
|
||||
};
|
||||
|
||||
// Decide whether the instrument pane (PianoRoll = STACK index 4) reveals the roll, from the
|
||||
// *committed* (snapped) window weights — so the keyboard↔roll transition lands on a stack snap
|
||||
// rather than at an arbitrary mid-drag height. Roll shows once the pane is past the smallest snap.
|
||||
rc.shared.instrument_show_roll = {
|
||||
let idx = 4i32 - state.window_top as i32;
|
||||
if idx >= 0 && (idx as usize) < state.window_count {
|
||||
let sum: f32 = state.weights[..state.window_count].iter().map(|w| w.max(0.0)).sum();
|
||||
let w = if sum > 0.0 { state.weights[idx as usize].max(0.0) / sum } else { 0.0 };
|
||||
w > 0.30 // 0.25 preset ⇒ keyboard only; 0.33/0.5/0.75 ⇒ keyboard + roll
|
||||
} else {
|
||||
true
|
||||
}
|
||||
};
|
||||
|
||||
stack::render(ui, stack_rect, rc, state, &pal);
|
||||
|
||||
if inspector_shown {
|
||||
inspector::render(ui, inspector_rect, region, rc, state, &pal, landscape);
|
||||
}
|
||||
|
||||
// Transport floor: drawn last = always on top, the persistent spine.
|
||||
transport::render(ui, transport_rect, &mut rc.shared, &pal);
|
||||
|
||||
// Omnibutton FAB (radial tool menu) — drawn above the stack region, on top of everything else.
|
||||
omni::render(ui, region, rc, state, &pal);
|
||||
|
||||
// Instrument-browser request from the music pane's header → show the Preset Browser fullscreen.
|
||||
if *rc.shared.open_instrument_browser {
|
||||
*rc.shared.open_instrument_browser = false;
|
||||
state.show_instruments = true;
|
||||
state.window_top = 5; // Node/Instrument band (PresetBrowser when show_instruments)
|
||||
state.window_count = 1;
|
||||
state.weights = [1.0, 1.0, 1.0];
|
||||
state.anim = None;
|
||||
}
|
||||
|
||||
// Top bar (filename + ⌕ palette + ⋯ commands). Its menus overlay the whole shell, so it's last.
|
||||
// Portrait: its own band at the top. Landscape: folded into the middle of the top pane header.
|
||||
if landscape {
|
||||
let hh = stack::header_height(false);
|
||||
let top_header = egui::Rect::from_min_max(
|
||||
egui::pos2(stack_rect.left(), region.top()),
|
||||
egui::pos2(stack_rect.right(), region.top() + hh),
|
||||
);
|
||||
topbar::render_inline(ui, top_header, available_rect, rc, state, &pal);
|
||||
} else {
|
||||
topbar::render(ui, topbar_rect, available_rect, rc, state, &pal);
|
||||
}
|
||||
|
||||
// Long-press context menu (populated by whichever pane was long-pressed). Persistent popup,
|
||||
// dispatched via pending_menu_actions.
|
||||
render_context_menu(ui, available_rect, rc);
|
||||
}
|
||||
|
||||
/// Render the pane-populated long-press context menu (`shared.mobile_context_menu`) as a persistent
|
||||
/// popup: it stays open until an item is chosen or the user taps outside it. Styled to match the
|
||||
/// timeline's context menu (default themed popup frame + full-width, touch-height items).
|
||||
fn render_context_menu(ui: &mut egui::Ui, available: egui::Rect, rc: &mut RenderContext) {
|
||||
let Some(menu) = rc.shared.mobile_context_menu.clone() else {
|
||||
return;
|
||||
};
|
||||
// Keep the popup on screen (rough clamp against its estimated size).
|
||||
let est = egui::vec2(200.0, menu.items.len() as f32 * ui.spacing().interact_size.y + 16.0);
|
||||
let pos = egui::pos2(
|
||||
menu.pos.x.min(available.right() - est.x - 8.0).max(available.left() + 8.0),
|
||||
menu.pos.y.min(available.bottom() - est.y - 8.0).max(available.top() + 8.0),
|
||||
);
|
||||
|
||||
let mut chosen: Option<crate::menu::MenuAction> = None;
|
||||
let area = egui::Area::new(ui.id().with("mobile_ctx_menu"))
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(pos)
|
||||
.interactable(true)
|
||||
.show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.set_min_width(180.0);
|
||||
for (label, action) in &menu.items {
|
||||
let w = ui.available_width();
|
||||
let (rect, resp) =
|
||||
ui.allocate_exact_size(egui::vec2(w, ui.spacing().interact_size.y), egui::Sense::click());
|
||||
if ui.is_rect_visible(rect) {
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(rect, 2.0, ui.visuals().widgets.hovered.bg_fill);
|
||||
}
|
||||
let tc = if resp.hovered() {
|
||||
ui.visuals().widgets.hovered.text_color()
|
||||
} else {
|
||||
ui.visuals().widgets.inactive.text_color()
|
||||
};
|
||||
ui.painter().text(
|
||||
rect.min + egui::vec2(10.0, (rect.height() - 14.0) / 2.0),
|
||||
egui::Align2::LEFT_TOP,
|
||||
label,
|
||||
egui::FontId::proportional(14.0),
|
||||
tc,
|
||||
);
|
||||
}
|
||||
if resp.clicked() {
|
||||
chosen = Some(*action);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Dismiss on item choice or a primary click outside the popup. (The secondary click that opened
|
||||
// it won't dismiss, so there's no just-opened race.)
|
||||
let primary_click = ui.input(|i| i.pointer.button_clicked(egui::PointerButton::Primary));
|
||||
let dismiss = chosen.is_some() || (primary_click && !area.response.contains_pointer());
|
||||
if let Some(action) = chosen {
|
||||
rc.shared.pending_menu_actions.push(action);
|
||||
}
|
||||
if dismiss {
|
||||
*rc.shared.mobile_context_menu = None;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
//! Omnibutton — a floating action button whose radial holds the active layer's drawing tools plus
|
||||
//! a "+New" petal (create layers / import / clip ops) and, when there are extra tools, a "⋯ more"
|
||||
//! petal that opens a full-tools grid. Tools drive `shared.selected_tool`; create actions dispatch
|
||||
//! `MenuAction`s. The radial fans up and to the left, away from the thumb. Pane-internal adds
|
||||
//! (nodes/notes/instruments) are handled inside their panes (P6), not here.
|
||||
|
||||
use eframe::egui;
|
||||
use lightningbeam_core::layer::{AnyLayer, LayerType};
|
||||
use lightningbeam_core::selection::FocusSelection;
|
||||
use lightningbeam_core::tool::Tool;
|
||||
|
||||
use super::{icons, MobileState, Palette};
|
||||
use crate::menu::MenuAction;
|
||||
use crate::RenderContext;
|
||||
|
||||
const FAB_R: f32 = 26.0;
|
||||
const IR: f32 = 20.0;
|
||||
const PRIMARY: [Tool; 14] = [
|
||||
Tool::Select,
|
||||
Tool::Draw,
|
||||
Tool::Transform,
|
||||
Tool::Rectangle,
|
||||
Tool::Ellipse,
|
||||
Tool::Line,
|
||||
Tool::Polygon,
|
||||
Tool::PaintBucket,
|
||||
Tool::Gradient,
|
||||
Tool::Eyedropper,
|
||||
Tool::Text,
|
||||
Tool::Erase,
|
||||
Tool::BezierEdit,
|
||||
Tool::Split,
|
||||
];
|
||||
const RING_CAP: usize = 10;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Special {
|
||||
More,
|
||||
New,
|
||||
}
|
||||
|
||||
fn tool_icon(t: Tool) -> &'static str {
|
||||
match t {
|
||||
Tool::Select | Tool::RegionSelect => icons::MOUSE_POINTER_2,
|
||||
Tool::SelectLasso => icons::LASSO_SELECT,
|
||||
Tool::Draw | Tool::Pencil | Tool::Pen => icons::PENCIL,
|
||||
Tool::Transform => icons::VECTOR_SQUARE,
|
||||
Tool::Rectangle => icons::SQUARE,
|
||||
Tool::Ellipse => icons::CIRCLE,
|
||||
Tool::Line => icons::MINUS,
|
||||
Tool::Polygon => icons::HEXAGON,
|
||||
Tool::PaintBucket => icons::PAINT_BUCKET,
|
||||
Tool::Gradient => icons::BLEND,
|
||||
Tool::Eyedropper => icons::PIPETTE,
|
||||
Tool::Text => icons::TYPE,
|
||||
Tool::Erase => icons::ERASER,
|
||||
Tool::BezierEdit => icons::PEN_TOOL,
|
||||
Tool::MagicWand | Tool::QuickSelect => icons::WAND_SPARKLES,
|
||||
Tool::Split => icons::SCISSORS,
|
||||
_ => icons::BRUSH,
|
||||
}
|
||||
}
|
||||
|
||||
fn active_layer_type(rc: &RenderContext) -> Option<LayerType> {
|
||||
rc.shared
|
||||
.active_layer_id
|
||||
.and_then(|id| rc.shared.action_executor.document().get_layer(&id))
|
||||
.map(|layer| match layer {
|
||||
AnyLayer::Vector(_) => LayerType::Vector,
|
||||
AnyLayer::Audio(_) => LayerType::Audio,
|
||||
AnyLayer::Video(_) => LayerType::Video,
|
||||
AnyLayer::Effect(_) => LayerType::Effect,
|
||||
AnyLayer::Group(_) => LayerType::Group,
|
||||
AnyLayer::Raster(_) => LayerType::Raster,
|
||||
AnyLayer::Text(_) => LayerType::Text,
|
||||
})
|
||||
}
|
||||
|
||||
/// The create-menu items: (label, icon, action, enabled). Split/Duplicate need a selected clip.
|
||||
fn create_items(rc: &RenderContext) -> Vec<(&'static str, &'static str, MenuAction, bool)> {
|
||||
let clip_sel = matches!(&*rc.shared.focus, FocusSelection::ClipInstances(ids) if !ids.is_empty());
|
||||
vec![
|
||||
("Vector", icons::PEN_TOOL, MenuAction::AddLayer, true),
|
||||
("Audio", icons::AUDIO_WAVEFORM, MenuAction::AddAudioTrack, true),
|
||||
("MIDI", icons::PIANO, MenuAction::AddMidiTrack, true),
|
||||
("Raster", icons::BRUSH, MenuAction::AddRasterLayer, true),
|
||||
("Video", icons::CLAPPERBOARD, MenuAction::AddVideoLayer, true),
|
||||
("Group", icons::FOLDER, MenuAction::Group, true),
|
||||
("Import", icons::FILE_PLUS, MenuAction::Import, true),
|
||||
("Split", icons::SCISSORS, MenuAction::SplitClip, clip_sel),
|
||||
("Duplicate", icons::COPY, MenuAction::DuplicateClip, clip_sel),
|
||||
]
|
||||
}
|
||||
|
||||
fn close_all(state: &mut MobileState) {
|
||||
state.omni_open = false;
|
||||
state.omni_grid_open = false;
|
||||
state.omni_create_open = false;
|
||||
}
|
||||
|
||||
pub fn render(ui: &mut egui::Ui, region: egui::Rect, rc: &mut RenderContext, state: &mut MobileState, pal: &Palette) {
|
||||
let ctx_tools: Vec<Tool> = Tool::for_layer_type(active_layer_type(rc)).to_vec();
|
||||
let primary: Vec<Tool> = PRIMARY
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|t| ctx_tools.contains(t))
|
||||
.take(RING_CAP)
|
||||
.collect();
|
||||
let has_more = ctx_tools.len() > primary.len();
|
||||
|
||||
// Tools are only relevant when the Stage is on screen. Off-Stage the omnibutton is purely a
|
||||
// "+New" create button.
|
||||
let stage_slot = super::STACK
|
||||
.iter()
|
||||
.position(|p| *p == super::StackPane::Stage)
|
||||
.unwrap_or(2);
|
||||
let stage_visible = (state.window_top..state.window_top + state.window_count).contains(&stage_slot);
|
||||
if !stage_visible {
|
||||
state.omni_open = false; // no tool radial off-Stage
|
||||
}
|
||||
|
||||
let fab_center = egui::pos2(region.right() - 18.0 - FAB_R, region.bottom() - 18.0 - FAB_R);
|
||||
|
||||
if state.omni_grid_open {
|
||||
// Full-tools grid.
|
||||
let cells: Vec<Cell> = ctx_tools
|
||||
.iter()
|
||||
.map(|t| Cell {
|
||||
icon: tool_icon(*t),
|
||||
label: t.display_name(),
|
||||
selected: *rc.shared.selected_tool == *t,
|
||||
enabled: true,
|
||||
})
|
||||
.collect();
|
||||
let (close, clicked) = draw_grid(ui, region, "Tools", &cells, pal);
|
||||
if let Some(i) = clicked {
|
||||
*rc.shared.selected_tool = ctx_tools[i];
|
||||
close_all(state);
|
||||
} else if close {
|
||||
close_all(state);
|
||||
}
|
||||
} else if state.omni_create_open {
|
||||
// Create grid.
|
||||
let items = create_items(rc);
|
||||
let cells: Vec<Cell> = items
|
||||
.iter()
|
||||
.map(|it| Cell {
|
||||
icon: it.1,
|
||||
label: it.0,
|
||||
selected: false,
|
||||
enabled: it.3,
|
||||
})
|
||||
.collect();
|
||||
let (close, clicked) = draw_grid(ui, region, "New", &cells, pal);
|
||||
if let Some(i) = clicked {
|
||||
rc.shared.pending_menu_actions.push(items[i].2);
|
||||
close_all(state);
|
||||
} else if close {
|
||||
close_all(state);
|
||||
}
|
||||
} else if state.omni_open {
|
||||
// Radial: scrim, then tool petals + special petals (more / new).
|
||||
let scrim = ui.interact(region, ui.id().with("mobile_omni_scrim"), egui::Sense::click());
|
||||
ui.painter().rect_filled(region, 0.0, pal.scrim);
|
||||
if scrim.clicked() {
|
||||
state.omni_open = false;
|
||||
}
|
||||
|
||||
let mut specials: Vec<Special> = Vec::new();
|
||||
if has_more {
|
||||
specials.push(Special::More);
|
||||
}
|
||||
specials.push(Special::New);
|
||||
let n = primary.len() + specials.len();
|
||||
|
||||
for k in 0..n {
|
||||
let frac = if n > 1 { k as f32 / (n as f32 - 1.0) } else { 0.5 };
|
||||
let deg = 74.0 + frac * 126.0; // 74°..200°, up and to the left
|
||||
let a = deg.to_radians();
|
||||
let radius = if k % 2 == 0 { 114.0 } else { 170.0 };
|
||||
let c = fab_center + egui::vec2(radius * a.cos(), -radius * a.sin());
|
||||
let rect = egui::Rect::from_center_size(c, egui::vec2(IR * 2.0, IR * 2.0));
|
||||
|
||||
if k < primary.len() {
|
||||
let t = primary[k];
|
||||
let resp = ui.interact(rect, ui.id().with(("mobile_omni_tool", k)), egui::Sense::click());
|
||||
let selected = *rc.shared.selected_tool == t;
|
||||
petal(ui, c, if selected { pal.accent } else { petal_bg(&resp, pal) }, tool_icon(t), if selected { pal.on_accent } else { pal.text }, pal);
|
||||
if resp.clicked() {
|
||||
*rc.shared.selected_tool = t;
|
||||
state.omni_open = false;
|
||||
}
|
||||
} else {
|
||||
match specials[k - primary.len()] {
|
||||
Special::More => {
|
||||
let resp = ui.interact(rect, ui.id().with("mobile_omni_more"), egui::Sense::click());
|
||||
petal(ui, c, petal_bg(&resp, pal), icons::MENU, pal.text, pal);
|
||||
if resp.clicked() {
|
||||
state.omni_grid_open = true;
|
||||
}
|
||||
}
|
||||
Special::New => {
|
||||
let resp = ui.interact(rect, ui.id().with("mobile_omni_new"), egui::Sense::click());
|
||||
petal(ui, c, pal.accent, icons::PLUS, pal.on_accent, pal);
|
||||
if resp.hovered() {
|
||||
ui.painter().circle_stroke(c, IR, egui::Stroke::new(1.5, pal.text));
|
||||
}
|
||||
if resp.clicked() {
|
||||
state.omni_create_open = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The FAB itself (on top). Closed → current tool icon; open → ✕.
|
||||
let fab_rect = egui::Rect::from_center_size(fab_center, egui::vec2(FAB_R * 2.0, FAB_R * 2.0));
|
||||
let fresp = ui.interact(fab_rect, ui.id().with("mobile_omni_fab"), egui::Sense::click());
|
||||
ui.painter().circle_filled(fab_center, FAB_R, pal.accent);
|
||||
let open = state.omni_open || state.omni_grid_open || state.omni_create_open;
|
||||
let glyph = if open {
|
||||
icons::X
|
||||
} else if stage_visible {
|
||||
tool_icon(*rc.shared.selected_tool)
|
||||
} else {
|
||||
icons::PLUS // off-Stage: a create button
|
||||
};
|
||||
ui.painter()
|
||||
.text(fab_center, egui::Align2::CENTER_CENTER, glyph, icons::font(22.0), pal.on_accent);
|
||||
if fresp.clicked() {
|
||||
if open {
|
||||
close_all(state);
|
||||
} else if stage_visible {
|
||||
state.omni_open = true;
|
||||
} else {
|
||||
state.omni_create_open = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn petal_bg(resp: &egui::Response, pal: &Palette) -> egui::Color32 {
|
||||
if resp.hovered() {
|
||||
pal.line
|
||||
} else {
|
||||
pal.surface_alt
|
||||
}
|
||||
}
|
||||
|
||||
fn petal(ui: &egui::Ui, c: egui::Pos2, bg: egui::Color32, glyph: &str, fg: egui::Color32, pal: &Palette) {
|
||||
ui.painter().circle_filled(c, IR, bg);
|
||||
ui.painter().circle_stroke(c, IR, egui::Stroke::new(1.0, pal.line));
|
||||
ui.painter().text(c, egui::Align2::CENTER_CENTER, glyph, icons::font(18.0), fg);
|
||||
}
|
||||
|
||||
struct Cell {
|
||||
icon: &'static str,
|
||||
label: &'static str,
|
||||
selected: bool,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
/// A modal grid sheet of icon+label cells. Returns (backdrop-tapped, Some(clicked-enabled-index)).
|
||||
fn draw_grid(ui: &mut egui::Ui, region: egui::Rect, title: &str, cells: &[Cell], pal: &Palette) -> (bool, Option<usize>) {
|
||||
let scrim = ui.interact(region, ui.id().with(("mobile_omni_gridscrim", title)), egui::Sense::click());
|
||||
ui.painter().rect_filled(region, 0.0, pal.scrim);
|
||||
|
||||
let panel = region.shrink2(egui::vec2(16.0, 40.0));
|
||||
ui.painter().rect_filled(panel, 14.0, pal.surface);
|
||||
ui.painter().rect_stroke(panel, 14.0, egui::Stroke::new(1.0, pal.line), egui::StrokeKind::Inside);
|
||||
ui.painter().text(
|
||||
egui::pos2(panel.left() + 16.0, panel.top() + 18.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
title,
|
||||
egui::FontId::proportional(14.0),
|
||||
pal.text,
|
||||
);
|
||||
|
||||
let cols = 4usize;
|
||||
let n = cells.len();
|
||||
let rows = n.div_ceil(cols).max(1);
|
||||
let grid = egui::Rect::from_min_max(
|
||||
egui::pos2(panel.left() + 10.0, panel.top() + 36.0),
|
||||
egui::pos2(panel.right() - 10.0, panel.bottom() - 10.0),
|
||||
);
|
||||
let cw = grid.width() / cols as f32;
|
||||
let chh = (grid.height() / rows as f32).min(96.0);
|
||||
let mut clicked = None;
|
||||
for (i, cell) in cells.iter().enumerate() {
|
||||
let col = (i % cols) as f32;
|
||||
let row = (i / cols) as f32;
|
||||
let r = egui::Rect::from_min_size(
|
||||
egui::pos2(grid.left() + col * cw, grid.top() + row * chh),
|
||||
egui::vec2(cw, chh),
|
||||
)
|
||||
.shrink(5.0);
|
||||
let resp = if cell.enabled {
|
||||
ui.interact(r, ui.id().with(("mobile_omni_cell", title, i)), egui::Sense::click())
|
||||
} else {
|
||||
ui.interact(r, ui.id().with(("mobile_omni_cell_off", title, i)), egui::Sense::hover())
|
||||
};
|
||||
let bg = if cell.selected {
|
||||
pal.accent
|
||||
} else if cell.enabled && resp.hovered() {
|
||||
pal.surface_alt
|
||||
} else {
|
||||
pal.surface
|
||||
};
|
||||
ui.painter().rect_filled(r, 10.0, bg);
|
||||
ui.painter().rect_stroke(r, 10.0, egui::Stroke::new(1.0, pal.line), egui::StrokeKind::Inside);
|
||||
let fg = if cell.selected {
|
||||
pal.on_accent
|
||||
} else if cell.enabled {
|
||||
pal.text
|
||||
} else {
|
||||
pal.line
|
||||
};
|
||||
ui.painter().text(
|
||||
egui::pos2(r.center().x, r.top() + r.height() * 0.38),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
cell.icon,
|
||||
icons::font(22.0),
|
||||
fg,
|
||||
);
|
||||
ui.painter().text(
|
||||
egui::pos2(r.center().x, r.bottom() - 12.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
cell.label,
|
||||
egui::FontId::proportional(9.5),
|
||||
if cell.selected { pal.on_accent } else if cell.enabled { pal.text_dim } else { pal.line },
|
||||
);
|
||||
if cell.enabled && resp.clicked() {
|
||||
clicked = Some(i);
|
||||
}
|
||||
}
|
||||
(scrim.clicked() && clicked.is_none(), clicked)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! The mobile UI's semantic color palette, sourced from the shared theme CSS variables so it
|
||||
//! matches the main UI and responds to light/dark/user themes. Built once per frame from the active
|
||||
//! [`Theme`](crate::theme::Theme) and passed (by `Copy`) into the mobile render functions, replacing
|
||||
//! the per-file hardcoded color constants.
|
||||
|
||||
use eframe::egui::{Color32, Context};
|
||||
|
||||
use crate::theme::Theme;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Palette {
|
||||
/// App/device background behind everything.
|
||||
pub bg: Color32,
|
||||
/// Panels, cards, bands, sheets.
|
||||
pub surface: Color32,
|
||||
/// Raised / hovered surface.
|
||||
pub surface_alt: Color32,
|
||||
/// Band headers, the top bar.
|
||||
pub header: Color32,
|
||||
/// Borders and dividers.
|
||||
pub line: Color32,
|
||||
/// Primary text / icons.
|
||||
pub text: Color32,
|
||||
/// Secondary (dim) text / icons.
|
||||
pub text_dim: Color32,
|
||||
/// Selection / active accent.
|
||||
pub accent: Color32,
|
||||
/// Text / icons drawn on top of `accent`.
|
||||
pub on_accent: Color32,
|
||||
/// Modal backdrop (translucent).
|
||||
pub scrim: Color32,
|
||||
/// Decorative category accents (intent picker, chips): coral, cyan, amber, pink, violet.
|
||||
pub accents: [Color32; 5],
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
pub fn from_theme(theme: &Theme, ctx: &Context) -> Self {
|
||||
let c = |name: &str, fb: Color32| theme.var(name, ctx).unwrap_or(fb);
|
||||
Self {
|
||||
bg: c("bg-app", Color32::from_rgb(0x2a, 0x2a, 0x2a)),
|
||||
surface: c("bg-panel", Color32::from_rgb(0x22, 0x22, 0x22)),
|
||||
surface_alt: c("bg-surface-raised", Color32::from_rgb(0x3f, 0x3f, 0x3f)),
|
||||
header: c("bg-header", Color32::from_rgb(0x35, 0x35, 0x35)),
|
||||
line: c("border-default", Color32::from_rgb(0x44, 0x44, 0x44)),
|
||||
text: c("text-primary", Color32::from_rgb(0xf6, 0xf6, 0xf6)),
|
||||
text_dim: c("text-secondary", Color32::from_rgb(0xaa, 0xaa, 0xaa)),
|
||||
accent: c("accent", Color32::from_rgb(0x39, 0x6c, 0xd8)),
|
||||
on_accent: c("text-on-accent", Color32::WHITE),
|
||||
scrim: c("scrim", Color32::from_rgba_unmultiplied(0x10, 0x14, 0x1a, 0xb0)),
|
||||
accents: [
|
||||
c("accent-coral", Color32::from_rgb(0xe8, 0x82, 0x6b)),
|
||||
c("accent-cyan", Color32::from_rgb(0x54, 0xc3, 0xe8)),
|
||||
c("accent-amber", Color32::from_rgb(0xf4, 0xa3, 0x40)),
|
||||
c("accent-pink", Color32::from_rgb(0xc7, 0x5b, 0x8a)),
|
||||
c("accent-violet", Color32::from_rgb(0x8a, 0x6e, 0xc0)),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
//! The vertical sliding-window stack engine.
|
||||
//!
|
||||
//! A window of 2–3 consecutive panes (from [`super::STACK`]) is visible. Dragging the dividers
|
||||
//! between visible panes and the top/bottom screen edges grows, shrinks, or slides the window via
|
||||
//! the operations below (verified against the user's transition table):
|
||||
//!
|
||||
//! ```text
|
||||
//! R1 upper divider, UP -> slide window DOWN one (top+=1)
|
||||
//! R4 upper divider, DOWN -> drop BOTTOM pane (count 3->2)
|
||||
//! R3 lower divider, UP -> drop TOP pane (top+=1, count 3->2)
|
||||
//! R2 lower divider, DOWN -> slide window UP one (top-=1)
|
||||
//! R5 bottom edge, UP -> grow at bottom; if already 3, slide down
|
||||
//! R6 top edge, DOWN -> grow at top; if already 3, slide up
|
||||
//! ```
|
||||
//!
|
||||
//! At count==2 the single divider is "upper" when dragged up (R1) and "lower" when dragged
|
||||
//! down (R2). The window content interpolates continuously during a drag and snaps on release.
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
use super::{icons, slot_path, LayoutAnim, MobileState, Palette, StackDrag, StackPane, STACK};
|
||||
use crate::RenderContext;
|
||||
|
||||
const N: usize = STACK.len();
|
||||
|
||||
/// Height of each band's drag header (and the bottom-edge footer). The whole header is the grab
|
||||
/// target — there's no thin divider bar.
|
||||
const HEADER_H: f32 = 52.0;
|
||||
/// Landscape headers are shorter — vertical space is scarce, and the top one hosts the app bar.
|
||||
const HEADER_H_LANDSCAPE: f32 = 34.0;
|
||||
/// Header height for the current orientation.
|
||||
pub fn header_height(is_portrait: bool) -> f32 {
|
||||
if is_portrait { HEADER_H } else { HEADER_H_LANDSCAPE }
|
||||
}
|
||||
/// Corner radius (px) for the rounded top of each header.
|
||||
const HEADER_RADIUS: u8 = 9;
|
||||
const FOOTER_H: f32 = 28.0;
|
||||
/// Width of a header right-side button (fullscreen, node toggle).
|
||||
const BTN_W: f32 = 44.0;
|
||||
/// Max pixels of drag to complete a window transition (so you don't drag half the screen).
|
||||
const TRIGGER_MAX: f32 = 150.0;
|
||||
|
||||
/// A draggable boundary of the stack.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Handle {
|
||||
TopEdge,
|
||||
/// Divider below visible pane `k` (between visible pane `k` and `k+1`).
|
||||
Divider(usize),
|
||||
BottomEdge,
|
||||
}
|
||||
|
||||
// --- R1..R6 as pure ops on (top, count) -> Option<(top, count)> ---
|
||||
|
||||
fn op_r1(top: usize, count: usize) -> Option<(usize, usize)> {
|
||||
(top + count < N).then(|| (top + 1, count)) // slide down
|
||||
}
|
||||
fn op_r2(top: usize, count: usize) -> Option<(usize, usize)> {
|
||||
(top > 0).then(|| (top - 1, count)) // slide up
|
||||
}
|
||||
fn op_r3(top: usize, count: usize) -> Option<(usize, usize)> {
|
||||
(count == 3).then(|| (top + 1, 2)) // drop top
|
||||
}
|
||||
fn op_r4(top: usize, count: usize) -> Option<(usize, usize)> {
|
||||
(count == 3).then(|| (top, 2)) // drop bottom
|
||||
}
|
||||
fn op_r5(top: usize, count: usize, max: usize) -> Option<(usize, usize)> {
|
||||
if count < max && top + count < N {
|
||||
Some((top, count + 1)) // grow bottom
|
||||
} else if count == max && top + count < N {
|
||||
Some((top + 1, count)) // slide down
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
fn op_r6(top: usize, count: usize, max: usize) -> Option<(usize, usize)> {
|
||||
if count < max && top > 0 {
|
||||
Some((top - 1, count + 1)) // grow top
|
||||
} else if count == max && top > 0 {
|
||||
Some((top - 1, count)) // slide up
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Given a handle and signed drag offset, resolve the target window config and progress `t`.
|
||||
/// Returns None if the drag direction has no valid operation (e.g. at a list boundary).
|
||||
fn resolve(
|
||||
handle: Handle,
|
||||
offset: f32,
|
||||
top: usize,
|
||||
count: usize,
|
||||
trigger: f32,
|
||||
max: usize,
|
||||
) -> Option<(usize, usize, f32)> {
|
||||
let going_up = offset < 0.0;
|
||||
let t = (offset.abs() / trigger.max(1.0)).clamp(0.0, 1.0);
|
||||
let target = match handle {
|
||||
Handle::TopEdge => (!going_up).then(|| op_r6(top, count, max)).flatten(),
|
||||
Handle::BottomEdge => going_up.then(|| op_r5(top, count, max)).flatten(),
|
||||
Handle::Divider(k) => {
|
||||
if count == 2 {
|
||||
if going_up { op_r1(top, count) } else { op_r2(top, count) }
|
||||
} else if k == 0 {
|
||||
// upper divider
|
||||
if going_up { op_r1(top, count) } else { op_r4(top, count) }
|
||||
} else {
|
||||
// lower divider
|
||||
if going_up { op_r3(top, count) } else { op_r2(top, count) }
|
||||
}
|
||||
}
|
||||
};
|
||||
target.map(|(tt, tc)| (tt, tc, t))
|
||||
}
|
||||
|
||||
// --- rect layout ---
|
||||
|
||||
/// Below/above these boundary positions, a divider release collapses a group → membership change.
|
||||
const COLLAPSE_LO: f32 = 0.12;
|
||||
const COLLAPSE_HI: f32 = 0.88;
|
||||
|
||||
// The only allowed pane-weight distributions per window size. Snapping to these keeps the minimum
|
||||
// pane height manageable (no pane below ~1/4).
|
||||
const PRESETS_1: [[f32; 3]; 1] = [[1.0, 0.0, 0.0]];
|
||||
const PRESETS_2: [[f32; 3]; 3] = [[0.25, 0.75, 0.0], [0.5, 0.5, 0.0], [0.75, 0.25, 0.0]];
|
||||
const PRESETS_3: [[f32; 3]; 3] = [
|
||||
[0.5, 0.25, 0.25],
|
||||
[1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0],
|
||||
[0.25, 0.25, 0.5],
|
||||
];
|
||||
|
||||
fn presets(count: usize) -> &'static [[f32; 3]] {
|
||||
match count {
|
||||
2 => &PRESETS_2,
|
||||
3 => &PRESETS_3,
|
||||
_ => &PRESETS_1,
|
||||
}
|
||||
}
|
||||
|
||||
/// The allowed preset nearest (L2) to the current weights.
|
||||
fn nearest_preset(cur: &[f32], count: usize) -> [f32; 3] {
|
||||
let dist = |p: &[f32; 3]| (0..count).map(|i| (p[i] - cur[i]).powi(2)).sum::<f32>();
|
||||
presets(count)
|
||||
.iter()
|
||||
.min_by(|a, b| dist(a).total_cmp(&dist(b)))
|
||||
.copied()
|
||||
.unwrap_or([1.0, 0.0, 0.0])
|
||||
}
|
||||
|
||||
// 3-pane snapping rides a single path parameter s in [0, 2] through the three presets, so the two
|
||||
// dividers move together and reach their snaps simultaneously. The dragged divider's boundary
|
||||
// position (pane0 for the upper divider; pane0+pane1 for the lower) maps onto s.
|
||||
const PATH3_UPPER: [f32; 3] = [0.5, 1.0 / 3.0, 0.25]; // pane0 at s = 0, 1, 2
|
||||
const PATH3_LOWER: [f32; 3] = [0.75, 2.0 / 3.0, 0.5]; // pane0+pane1 at s = 0, 1, 2
|
||||
/// A pane grown beyond this collapses the 3-pane window to 2 panes on release.
|
||||
const COLLAPSE_GROW: f32 = 0.66;
|
||||
|
||||
fn lerp3(a: [f32; 3], b: [f32; 3], t: f32) -> [f32; 3] {
|
||||
[
|
||||
lerp_f(a[0], b[0], t),
|
||||
lerp_f(a[1], b[1], t),
|
||||
lerp_f(a[2], b[2], t),
|
||||
]
|
||||
}
|
||||
|
||||
/// Weights along the 3-pane preset path at parameter `s` ∈ [0, 2].
|
||||
fn path3(s: f32) -> [f32; 3] {
|
||||
let s = s.clamp(0.0, 2.0);
|
||||
if s <= 1.0 {
|
||||
lerp3(PRESETS_3[0], PRESETS_3[1], s)
|
||||
} else {
|
||||
lerp3(PRESETS_3[1], PRESETS_3[2], s - 1.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Path parameter for divider `k` whose boundary position is `b` (within the path's range).
|
||||
fn s_from_boundary(k: usize, b: f32) -> f32 {
|
||||
let pts = if k == 0 { PATH3_UPPER } else { PATH3_LOWER };
|
||||
if b >= pts[1] {
|
||||
(pts[0] - b) / (pts[0] - pts[1]) // 0 at pts[0] … 1 at pts[1]
|
||||
} else {
|
||||
1.0 + (pts[1] - b) / (pts[1] - pts[2]) // 1 at pts[1] … 2 at pts[2]
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3-pane path boundary range for divider `k`: (min, max) of its position across the presets.
|
||||
fn path3_range(k: usize) -> (f32, f32) {
|
||||
let pts = if k == 0 { PATH3_UPPER } else { PATH3_LOWER };
|
||||
(pts[2], pts[0])
|
||||
}
|
||||
|
||||
/// Live weights while dragging divider `k` to boundary `b` in a 3-pane window: follow the linked
|
||||
/// path within range, and beyond it group-resize from the nearer path endpoint (so the motion is
|
||||
/// continuous across the extreme presets — no jump in the other divider).
|
||||
fn live_weights3(k: usize, b_unclamped: f32) -> [f32; 3] {
|
||||
let (lo, hi) = path3_range(k);
|
||||
if b_unclamped >= lo && b_unclamped <= hi {
|
||||
path3(s_from_boundary(k, b_unclamped))
|
||||
} else {
|
||||
let anchor = if b_unclamped > hi { path3(0.0) } else { path3(2.0) };
|
||||
let (bmin, bmax) = boundary_bounds(3, k);
|
||||
to_arr(&weights_for_boundary(&anchor, k, b_unclamped.clamp(bmin, bmax)))
|
||||
}
|
||||
}
|
||||
/// Minimum normalized size a pane may be squeezed to during a live divider drag.
|
||||
const MIN_FRAC: f32 = 0.05;
|
||||
/// Duration (seconds) of the ease into a snapped divider position.
|
||||
const SNAP_ANIM_SECS: f64 = 0.10;
|
||||
|
||||
fn ease_out(p: f32) -> f32 {
|
||||
1.0 - (1.0 - p).powi(3)
|
||||
}
|
||||
|
||||
/// Normalized pane weights (the first `count` stored weights, summing to 1).
|
||||
fn nweights(weights: &[f32; 3], count: usize) -> Vec<f32> {
|
||||
let mut w: Vec<f32> = weights[..count].iter().map(|x| x.max(0.0001)).collect();
|
||||
let s: f32 = w.iter().sum();
|
||||
if s > 0.0 {
|
||||
for x in &mut w {
|
||||
*x /= s;
|
||||
}
|
||||
} else {
|
||||
let e = 1.0 / count as f32;
|
||||
w.iter_mut().for_each(|x| *x = e);
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// The bottom Y of the given stack slot's band within `region` (using the current window +
|
||||
/// weights), or None if that slot isn't in the visible window. Used to decide whether the
|
||||
/// inspector sheet would cover the selected pane.
|
||||
#[allow(dead_code)] // kept for pane-coverage heuristics
|
||||
pub fn pane_bottom_in(state: &MobileState, region: egui::Rect, slot: usize) -> Option<f32> {
|
||||
let (top, count) = (state.window_top, state.window_count);
|
||||
if slot < top || slot >= top + count {
|
||||
return None;
|
||||
}
|
||||
let nw = nweights(&state.weights, count);
|
||||
let cum: f32 = nw[..=(slot - top)].iter().sum();
|
||||
Some(region.top() + cum * region.height())
|
||||
}
|
||||
|
||||
/// Lay out `count` panes in `rect` using normalized weights `nw`.
|
||||
fn config_rects(top: usize, count: usize, rect: egui::Rect, nw: &[f32]) -> Vec<(usize, egui::Rect)> {
|
||||
let h = rect.height();
|
||||
let mut out = Vec::with_capacity(count);
|
||||
let mut y = rect.top();
|
||||
for i in 0..count {
|
||||
let ph = nw[i] * h;
|
||||
out.push((
|
||||
top + i,
|
||||
egui::Rect::from_min_max(egui::pos2(rect.left(), y), egui::pos2(rect.right(), y + ph)),
|
||||
));
|
||||
y += ph;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn lerp_f(a: f32, b: f32, t: f32) -> f32 {
|
||||
a + (b - a) * t
|
||||
}
|
||||
fn lerp_rect(a: egui::Rect, b: egui::Rect, t: f32) -> egui::Rect {
|
||||
egui::Rect::from_min_max(
|
||||
egui::pos2(lerp_f(a.min.x, b.min.x, t), lerp_f(a.min.y, b.min.y, t)),
|
||||
egui::pos2(lerp_f(a.max.x, b.max.x, t), lerp_f(a.max.y, b.max.y, t)),
|
||||
)
|
||||
}
|
||||
fn collapsed(rect: egui::Rect, at_top: bool) -> egui::Rect {
|
||||
let y = if at_top { rect.top() } else { rect.bottom() };
|
||||
egui::Rect::from_min_max(egui::pos2(rect.left(), y), egui::pos2(rect.right(), y))
|
||||
}
|
||||
|
||||
/// Allowed range of divider `k`'s boundary position (normalized) given MIN_FRAC per pane.
|
||||
/// The boundary splits the window into the group above (panes 0..=k) and below (panes k+1..).
|
||||
fn boundary_bounds(count: usize, k: usize) -> (f32, f32) {
|
||||
let above = (k + 1) as f32;
|
||||
let below = (count - 1 - k) as f32;
|
||||
(above * MIN_FRAC, 1.0 - below * MIN_FRAC)
|
||||
}
|
||||
|
||||
/// New normalized weights when divider `k` is moved to boundary position `b`: the panes above the
|
||||
/// divider are scaled to fill `[0, b]` and those below to fill `[b, 1]`, each group keeping its
|
||||
/// internal proportions. This makes the *other* dividers in the group move with the dragged one.
|
||||
fn weights_for_boundary(nw: &[f32], k: usize, b: f32) -> Vec<f32> {
|
||||
let count = nw.len();
|
||||
let above_sum: f32 = nw[..=k].iter().sum();
|
||||
let below_sum: f32 = nw[k + 1..].iter().sum();
|
||||
let mut w = nw.to_vec();
|
||||
if above_sum > 0.0 {
|
||||
let s = b / above_sum;
|
||||
for x in &mut w[..=k] {
|
||||
*x *= s;
|
||||
}
|
||||
}
|
||||
if below_sum > 0.0 {
|
||||
let s = (1.0 - b) / below_sum;
|
||||
for x in &mut w[k + 1..count] {
|
||||
*x *= s;
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
fn to_arr(v: &[f32]) -> [f32; 3] {
|
||||
let mut a = [0.0; 3];
|
||||
for (i, x) in v.iter().take(3).enumerate() {
|
||||
a[i] = *x;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
fn even_arr(count: usize) -> [f32; 3] {
|
||||
let mut a = [0.0; 3];
|
||||
let e = 1.0 / count as f32;
|
||||
for x in a.iter_mut().take(count) {
|
||||
*x = e;
|
||||
}
|
||||
a
|
||||
}
|
||||
|
||||
/// Interpolate between two precomputed rect lists by `t` (used for edge membership transitions).
|
||||
fn interp_layout(
|
||||
c: &[(usize, egui::Rect)],
|
||||
tt: &[(usize, egui::Rect)],
|
||||
top_c: usize,
|
||||
top_t: usize,
|
||||
t: f32,
|
||||
rect: egui::Rect,
|
||||
) -> Vec<(usize, egui::Rect)> {
|
||||
let find = |v: &[(usize, egui::Rect)], slot: usize| v.iter().find(|(s, _)| *s == slot).map(|(_, r)| *r);
|
||||
let lo = c.first().map(|(s, _)| *s).unwrap_or(0).min(tt.first().map(|(s, _)| *s).unwrap_or(0));
|
||||
let hi = c.last().map(|(s, _)| *s + 1).unwrap_or(0).max(tt.last().map(|(s, _)| *s + 1).unwrap_or(0));
|
||||
let mut out = Vec::new();
|
||||
for slot in lo..hi {
|
||||
let r = match (find(c, slot), find(tt, slot)) {
|
||||
(Some(rc), Some(rt)) => lerp_rect(rc, rt, t),
|
||||
(Some(rc), None) => lerp_rect(rc, collapsed(rect, slot < top_t), t), // exiting
|
||||
(None, Some(rt)) => lerp_rect(collapsed(rect, slot < top_c), rt, t), // entering
|
||||
(None, None) => continue,
|
||||
};
|
||||
out.push((slot, r));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// --- rendering ---
|
||||
|
||||
/// The interaction (drag) target for a band's boundary is its full-width header bar. Bands are
|
||||
/// laid out in the area above a reserved bottom footer (the BottomEdge handle). Band 0's header is
|
||||
/// the TopEdge handle; band i's header (i≥1) is the divider above it; the footer is the BottomEdge.
|
||||
pub fn render(ui: &mut egui::Ui, rect: egui::Rect, rc: &mut RenderContext, state: &mut MobileState, pal: &Palette) {
|
||||
let top = state.window_top;
|
||||
let count = state.window_count;
|
||||
// Landscape caps the window at 2 panes; portrait allows 3.
|
||||
let max_panes = if rc.shared.is_portrait { 3 } else { 2 };
|
||||
let header_h = header_height(rc.shared.is_portrait);
|
||||
|
||||
// Reserve a footer bar at the very bottom for the BottomEdge handle.
|
||||
let footer_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(rect.left(), rect.bottom() - FOOTER_H),
|
||||
rect.max,
|
||||
);
|
||||
let content_area = egui::Rect::from_min_max(
|
||||
rect.min,
|
||||
egui::pos2(rect.right(), footer_rect.top()),
|
||||
);
|
||||
let pane_h = content_area.height() / count as f32;
|
||||
let trigger = pane_h.min(TRIGGER_MAX);
|
||||
|
||||
let now = ui.input(|i| i.time);
|
||||
// Resting band rects from the committed weights — used for interaction so handles sit at their
|
||||
// final positions even while the visuals animate.
|
||||
let nw = nweights(&state.weights, count);
|
||||
let rest_bands = config_rects(top, count, content_area, &nw);
|
||||
|
||||
// The draw layout: a live drag, an in-flight layout ease, or the resting config.
|
||||
let draw_layout = if let Some(d) = state.drag {
|
||||
match d.handle {
|
||||
Handle::Divider(k) if k + 1 < count => {
|
||||
// Live resize: move divider k's boundary. In 3-pane the dividers are linked along the
|
||||
// preset path; in 2-pane it's a simple group resize.
|
||||
let off_frac = d.offset / content_area.height().max(1.0);
|
||||
let b0: f32 = nw[..=k].iter().sum();
|
||||
let b = b0 + off_frac;
|
||||
let w = if count == 3 {
|
||||
live_weights3(k, b)
|
||||
} else {
|
||||
let (bmin, bmax) = boundary_bounds(count, k);
|
||||
to_arr(&weights_for_boundary(&nw, k, b.clamp(bmin, bmax)))
|
||||
};
|
||||
config_rects(top, count, content_area, &nweights(&w, count))
|
||||
}
|
||||
Handle::BottomEdge if count == 1 && top + 1 < N => {
|
||||
// Continuous reveal: dragging the bottom edge up grows the pane below out of the
|
||||
// bottom, its divider tracking the finger across the FULL height (not just `trigger`),
|
||||
// so one drag sweeps the current pane → split → revealed-pane-fullscreen.
|
||||
let frac = (-d.offset / content_area.height().max(1.0)).clamp(0.0, 1.0);
|
||||
config_rects(top, 2, content_area, &nweights(&[1.0 - frac, frac, 0.0], 2))
|
||||
}
|
||||
Handle::TopEdge if count == 1 && top > 0 => {
|
||||
// Symmetric reveal of the pane above: dragging the top edge down grows it from the top.
|
||||
let frac = (d.offset / content_area.height().max(1.0)).clamp(0.0, 1.0);
|
||||
config_rects(top - 1, 2, content_area, &nweights(&[frac, 1.0 - frac, 0.0], 2))
|
||||
}
|
||||
Handle::BottomEdge if count == 2 && max_panes == 2 => {
|
||||
// 2-pane (landscape) → 1-pane reveal: dragging the bottom edge up first slides the
|
||||
// window down to reveal the pane below, then collapses onto it — the whole sweep
|
||||
// mapped over the FULL height so the dragged boundary reaches the top (rather than
|
||||
// stalling at the even split after the slide).
|
||||
let frac = (-d.offset / content_area.height().max(1.0)).clamp(0.0, 1.0);
|
||||
let even2 = nweights(&even_arr(2), 2);
|
||||
let even1 = nweights(&even_arr(1), 1);
|
||||
if top + 2 < N {
|
||||
if frac <= 0.5 {
|
||||
let from = config_rects(top, 2, content_area, &even2);
|
||||
let to = config_rects(top + 1, 2, content_area, &even2);
|
||||
interp_layout(&from, &to, top, top + 1, frac / 0.5, content_area)
|
||||
} else {
|
||||
let from = config_rects(top + 1, 2, content_area, &even2);
|
||||
let to = config_rects(top + 2, 1, content_area, &even1);
|
||||
interp_layout(&from, &to, top + 1, top + 2, (frac - 0.5) / 0.5, content_area)
|
||||
}
|
||||
} else {
|
||||
// No pane below → just collapse onto the bottom pane.
|
||||
let from = config_rects(top, 2, content_area, &even2);
|
||||
let to = config_rects(top + 1, 1, content_area, &even1);
|
||||
interp_layout(&from, &to, top, top + 1, frac, content_area)
|
||||
}
|
||||
}
|
||||
Handle::TopEdge if count == 2 && max_panes == 2 => {
|
||||
// Symmetric 2→1 reveal from the top: dragging the top edge down slides the window up
|
||||
// to reveal the pane above, then collapses onto it.
|
||||
let frac = (d.offset / content_area.height().max(1.0)).clamp(0.0, 1.0);
|
||||
let even2 = nweights(&even_arr(2), 2);
|
||||
let even1 = nweights(&even_arr(1), 1);
|
||||
if top > 0 {
|
||||
if frac <= 0.5 {
|
||||
let from = config_rects(top, 2, content_area, &even2);
|
||||
let to = config_rects(top - 1, 2, content_area, &even2);
|
||||
interp_layout(&from, &to, top, top - 1, frac / 0.5, content_area)
|
||||
} else {
|
||||
let from = config_rects(top - 1, 2, content_area, &even2);
|
||||
let to = config_rects(top - 1, 1, content_area, &even1);
|
||||
interp_layout(&from, &to, top - 1, top - 1, (frac - 0.5) / 0.5, content_area)
|
||||
}
|
||||
} else {
|
||||
// No pane above → collapse onto the top pane (drop the bottom).
|
||||
let from = config_rects(top, 2, content_area, &even2);
|
||||
let to = config_rects(top, 1, content_area, &even1);
|
||||
interp_layout(&from, &to, top, top, frac, content_area)
|
||||
}
|
||||
}
|
||||
_ => resolve(d.handle, d.offset, top, count, trigger, max_panes)
|
||||
.map(|(tt, tc, t)| {
|
||||
let target = config_rects(tt, tc, content_area, &nweights(&even_arr(tc), tc));
|
||||
interp_layout(&rest_bands, &target, top, tt, t, content_area)
|
||||
})
|
||||
.unwrap_or_else(|| rest_bands.clone()),
|
||||
}
|
||||
} else if let Some(a) = state.anim {
|
||||
let p = (((now - a.start) / SNAP_ANIM_SECS) as f32).clamp(0.0, 1.0);
|
||||
if p >= 1.0 {
|
||||
state.anim = None;
|
||||
rest_bands.clone()
|
||||
} else {
|
||||
ui.ctx().request_repaint();
|
||||
let e = ease_out(p);
|
||||
let from = config_rects(a.from_top, a.from_count, content_area, &nweights(&a.from_w, a.from_count));
|
||||
let to = config_rects(a.to_top, a.to_count, content_area, &nweights(&a.to_w, a.to_count));
|
||||
interp_layout(&from, &to, a.from_top, a.to_top, e, content_area)
|
||||
}
|
||||
} else {
|
||||
rest_bands.clone()
|
||||
};
|
||||
|
||||
// 1) Pane content, carving the header off the top of each band.
|
||||
for (slot, brect) in &draw_layout {
|
||||
let hh = header_h.min(brect.height());
|
||||
let content_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(brect.left(), brect.top() + hh),
|
||||
brect.max,
|
||||
);
|
||||
if content_rect.height() > 1.0 {
|
||||
let sp = STACK[*slot];
|
||||
super::surface::render_surface_fullbleed(
|
||||
ui,
|
||||
content_rect,
|
||||
&slot_path(*slot),
|
||||
sp.pane_type(state.show_instruments),
|
||||
rc,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Header visuals (animated positions). The fullscreen icon shows "restore" when a single
|
||||
// pane fills the stack.
|
||||
let fullscreen = draw_layout.len() == 1;
|
||||
for (slot, brect) in &draw_layout {
|
||||
if brect.height() < 6.0 {
|
||||
continue;
|
||||
}
|
||||
let hr = egui::Rect::from_min_max(
|
||||
brect.left_top(),
|
||||
egui::pos2(brect.right(), brect.top() + header_h.min(brect.height())),
|
||||
);
|
||||
draw_header(ui, hr, STACK[*slot], state.show_instruments, fullscreen, pal);
|
||||
}
|
||||
draw_footer(ui, footer_rect, top + count >= N, pal);
|
||||
|
||||
// 3) Interactions on the resting header/footer rects (added last → they win the press).
|
||||
handle_interactions(ui, &rest_bands, content_area, footer_rect, trigger, now, state, max_panes, header_h);
|
||||
}
|
||||
|
||||
fn draw_header(ui: &egui::Ui, hr: egui::Rect, sp: StackPane, show_instruments: bool, fullscreen: bool, pal: &Palette) {
|
||||
let p = ui.painter();
|
||||
// Rounded top corners so the header reads as a tab atop the pane; square at the bottom where
|
||||
// it meets the pane content.
|
||||
p.rect_filled(
|
||||
hr,
|
||||
egui::CornerRadius { nw: HEADER_RADIUS, ne: HEADER_RADIUS, sw: 0, se: 0 },
|
||||
pal.header,
|
||||
);
|
||||
p.hline(hr.x_range(), hr.bottom(), egui::Stroke::new(1.0, pal.line));
|
||||
let cy = hr.center().y;
|
||||
// Grip glyph on the left (Lucide).
|
||||
p.text(
|
||||
egui::pos2(hr.left() + 15.0, cy),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::GRIP_HORIZONTAL,
|
||||
icons::font(16.0),
|
||||
pal.text_dim,
|
||||
);
|
||||
p.text(
|
||||
egui::pos2(hr.left() + 32.0, cy),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
sp.label(show_instruments),
|
||||
egui::FontId::proportional(15.0),
|
||||
pal.text,
|
||||
);
|
||||
// Right-side buttons: fullscreen / restore rightmost, Node/Instrument toggle just left of it.
|
||||
p.text(
|
||||
egui::pos2(hr.right() - BTN_W * 0.5, cy),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
if fullscreen { icons::MINIMIZE } else { icons::MAXIMIZE },
|
||||
icons::font(17.0),
|
||||
pal.text_dim,
|
||||
);
|
||||
if sp == StackPane::NodeInstrument {
|
||||
p.text(
|
||||
egui::pos2(hr.right() - BTN_W * 1.5, cy),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::ARROW_LEFT_RIGHT,
|
||||
icons::font(17.0),
|
||||
pal.accent,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_footer(ui: &egui::Ui, fr: egui::Rect, at_end: bool, pal: &Palette) {
|
||||
let p = ui.painter();
|
||||
p.rect_filled(fr, 0.0, pal.header);
|
||||
p.hline(fr.x_range(), fr.top(), egui::Stroke::new(1.0, pal.line));
|
||||
let col = if at_end { pal.line } else { pal.text_dim };
|
||||
let cy = fr.center().y;
|
||||
let galley = p.layout_no_wrap(
|
||||
"pull up for more".to_string(),
|
||||
egui::FontId::proportional(11.0),
|
||||
col,
|
||||
);
|
||||
let total_w = 22.0 + galley.size().x;
|
||||
let start_x = fr.center().x - total_w * 0.5;
|
||||
p.text(
|
||||
egui::pos2(start_x + 8.0, cy),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::CHEVRONS_UP,
|
||||
icons::font(14.0),
|
||||
col,
|
||||
);
|
||||
let gy = cy - galley.size().y * 0.5;
|
||||
p.galley(egui::pos2(start_x + 22.0, gy), galley, col);
|
||||
}
|
||||
|
||||
fn handle_key(h: Handle) -> (usize, usize) {
|
||||
match h {
|
||||
Handle::TopEdge => (0, 0),
|
||||
Handle::Divider(k) => (1, k + 1),
|
||||
Handle::BottomEdge => (2, 0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle a slot between filling the stack (count==1) and a 2-pane split with an adjacent pane.
|
||||
fn toggle_fullscreen(state: &mut MobileState, slot: usize, now: f64, max: usize) {
|
||||
if state.window_count == 1 && state.window_top == slot {
|
||||
// Restore: split with the pane below if possible, else above.
|
||||
if let Some((t, c)) = op_r5(slot, 1, max).or_else(|| op_r6(slot, 1, max)) {
|
||||
set_window(state, t, c, now);
|
||||
}
|
||||
} else {
|
||||
set_window(state, slot, 1, now);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_interactions(
|
||||
ui: &mut egui::Ui,
|
||||
rest_bands: &[(usize, egui::Rect)],
|
||||
content_area: egui::Rect,
|
||||
footer_rect: egui::Rect,
|
||||
trigger: f32,
|
||||
now: f64,
|
||||
state: &mut MobileState,
|
||||
max: usize,
|
||||
header_h: f32,
|
||||
) {
|
||||
// (handle, header_rect, slot) — slot is Some for band headers, None for the footer.
|
||||
let mut handles: Vec<(Handle, egui::Rect, Option<usize>)> = Vec::new();
|
||||
for (i, (slot, brect)) in rest_bands.iter().enumerate() {
|
||||
let hr = egui::Rect::from_min_max(
|
||||
brect.left_top(),
|
||||
egui::pos2(brect.right(), brect.top() + header_h.min(brect.height())),
|
||||
);
|
||||
let handle = if i == 0 { Handle::TopEdge } else { Handle::Divider(i - 1) };
|
||||
handles.push((handle, hr, Some(*slot)));
|
||||
}
|
||||
handles.push((Handle::BottomEdge, footer_rect, None));
|
||||
|
||||
for (handle, hrect, slot_opt) in handles {
|
||||
let id = ui.id().with(("mobile_stack_handle", handle_key(handle)));
|
||||
let resp = ui.interact(hrect, id, egui::Sense::click_and_drag());
|
||||
|
||||
// Right-side header buttons are interacted AFTER the header (so they're on top and win the
|
||||
// press there); the rest of the header drives the drag.
|
||||
if let Some(slot) = slot_opt {
|
||||
let fs = egui::Rect::from_min_max(
|
||||
egui::pos2(hrect.right() - BTN_W, hrect.top()),
|
||||
hrect.max,
|
||||
);
|
||||
let fsresp = ui.interact(fs, ui.id().with(("mobile_fs", slot)), egui::Sense::click());
|
||||
if fsresp.clicked() {
|
||||
toggle_fullscreen(state, slot, now, max);
|
||||
}
|
||||
if STACK[slot] == StackPane::NodeInstrument {
|
||||
let nt = egui::Rect::from_min_max(
|
||||
egui::pos2(hrect.right() - 2.0 * BTN_W, hrect.top()),
|
||||
egui::pos2(hrect.right() - BTN_W, hrect.bottom()),
|
||||
);
|
||||
let ntresp = ui.interact(nt, ui.id().with("mobile_node_toggle"), egui::Sense::click());
|
||||
if ntresp.clicked() {
|
||||
state.show_instruments = !state.show_instruments;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if resp.drag_started() {
|
||||
state.drag = Some(StackDrag { handle, offset: 0.0 });
|
||||
state.anim = None; // a fresh drag cancels any in-flight ease
|
||||
}
|
||||
if resp.dragged() {
|
||||
if let Some(d) = &mut state.drag {
|
||||
if d.handle == handle {
|
||||
d.offset += resp.drag_delta().y;
|
||||
}
|
||||
}
|
||||
}
|
||||
if resp.drag_stopped() {
|
||||
if let Some(d) = state.drag.take() {
|
||||
commit_drag(d, state, content_area, trigger, now, max);
|
||||
}
|
||||
}
|
||||
if resp.hovered() || state.drag.map(|d| d.handle == handle).unwrap_or(false) {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeVertical);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn commit_drag(d: StackDrag, state: &mut MobileState, content_area: egui::Rect, trigger: f32, now: f64, max: usize) {
|
||||
let h = content_area.height().max(1.0);
|
||||
match d.handle {
|
||||
Handle::Divider(k) if k + 1 < state.window_count => {
|
||||
commit_divider(state, k, d.offset / h, now);
|
||||
}
|
||||
Handle::BottomEdge if state.window_count == 1 && state.window_top + 1 < N => {
|
||||
// Snap the continuous reveal: near the top → revealed pane fullscreen; barely moved →
|
||||
// back to the current pane; in between → a 2-pane split at the nearest preset.
|
||||
let top = state.window_top;
|
||||
let frac = (-d.offset / h).clamp(0.0, 1.0);
|
||||
let from_w = [1.0 - frac, frac, 0.0];
|
||||
if frac >= COLLAPSE_HI {
|
||||
begin_anim(state, top, 2, from_w, top + 1, 1, even_arr(1), 0.0, now);
|
||||
} else if frac <= COLLAPSE_LO {
|
||||
begin_anim(state, top, 2, from_w, top, 1, even_arr(1), 0.0, now);
|
||||
} else {
|
||||
begin_anim(state, top, 2, from_w, top, 2, nearest_preset(&from_w, 2), 0.0, now);
|
||||
}
|
||||
}
|
||||
Handle::TopEdge if state.window_count == 1 && state.window_top > 0 => {
|
||||
let top = state.window_top;
|
||||
let frac = (d.offset / h).clamp(0.0, 1.0);
|
||||
let from_w = [frac, 1.0 - frac, 0.0];
|
||||
if frac >= COLLAPSE_HI {
|
||||
begin_anim(state, top - 1, 2, from_w, top - 1, 1, even_arr(1), 0.0, now);
|
||||
} else if frac <= COLLAPSE_LO {
|
||||
begin_anim(state, top - 1, 2, from_w, top, 1, even_arr(1), 0.0, now);
|
||||
} else {
|
||||
begin_anim(state, top - 1, 2, from_w, top - 1, 2, nearest_preset(&from_w, 2), 0.0, now);
|
||||
}
|
||||
}
|
||||
Handle::BottomEdge if state.window_count == 2 && max == 2 => {
|
||||
// Snap the two-phase 2→1 reveal to match the preview's phases: past the midpoint (phase 2,
|
||||
// collapsing) → revealed pane fullscreen; a middling drag (phase 1, sliding) → the next
|
||||
// 2-pane split; barely moved → stay put.
|
||||
let top = state.window_top;
|
||||
let frac = (-d.offset / h).clamp(0.0, 1.0);
|
||||
let even2 = even_arr(2);
|
||||
if top + 2 < N {
|
||||
if frac >= 0.5 {
|
||||
let t = ((frac - 0.5) / 0.5).clamp(0.0, 1.0);
|
||||
begin_anim(state, top + 1, 2, even2, top + 2, 1, even_arr(1), t, now);
|
||||
} else if frac > COLLAPSE_LO {
|
||||
let t = (frac / 0.5).clamp(0.0, 1.0);
|
||||
begin_anim(state, top, 2, even2, top + 1, 2, even2, t, now);
|
||||
}
|
||||
// else: barely moved → stay on the current [top, top+1] split.
|
||||
} else if frac >= 0.5 {
|
||||
begin_anim(state, top, 2, even2, top + 1, 1, even_arr(1), frac, now);
|
||||
}
|
||||
}
|
||||
Handle::TopEdge if state.window_count == 2 && max == 2 => {
|
||||
// Symmetric snap for the top-edge 2→1 reveal.
|
||||
let top = state.window_top;
|
||||
let frac = (d.offset / h).clamp(0.0, 1.0);
|
||||
let even2 = even_arr(2);
|
||||
if top > 0 {
|
||||
if frac >= 0.5 {
|
||||
let t = ((frac - 0.5) / 0.5).clamp(0.0, 1.0);
|
||||
begin_anim(state, top - 1, 2, even2, top - 1, 1, even_arr(1), t, now);
|
||||
} else if frac > COLLAPSE_LO {
|
||||
let t = (frac / 0.5).clamp(0.0, 1.0);
|
||||
begin_anim(state, top, 2, even2, top - 1, 2, even2, t, now);
|
||||
}
|
||||
// else: barely moved → stay on the current split.
|
||||
} else if frac >= 0.5 {
|
||||
begin_anim(state, top, 2, even2, top, 1, even_arr(1), frac, now);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Edges (and degenerate dividers): membership transition. Animate from the current
|
||||
// config to the new one, continuing from where the drag's interp left off (~progress t).
|
||||
let top = state.window_top;
|
||||
let count = state.window_count;
|
||||
if let Some((tt, tc, t)) = resolve(d.handle, d.offset, top, count, trigger, max) {
|
||||
if t >= 0.5 {
|
||||
let from_w = to_arr(&nweights(&state.weights, count));
|
||||
begin_anim(state, top, count, from_w, tt, tc, even_arr(tc), t, now);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply a divider release. 3-pane and 2-pane have different snap rules (see below). Either way the
|
||||
/// result is eased in from whatever was on screen at release.
|
||||
fn commit_divider(state: &mut MobileState, k: usize, offset_frac: f32, now: f64) {
|
||||
let top = state.window_top;
|
||||
let count = state.window_count;
|
||||
let nw = nweights(&state.weights, count);
|
||||
let b0: f32 = nw[..=k].iter().sum();
|
||||
let b = b0 + offset_frac; // unclamped boundary position of divider k
|
||||
|
||||
if count == 3 {
|
||||
// `from` = what's on screen at release.
|
||||
let from_w = live_weights3(k, b);
|
||||
// Sizes of the two extreme panes after this drag, to test the "grown past 66%" rule.
|
||||
let pane_top = from_w[0]; // grown when dragging the upper divider down
|
||||
let pane_bot = from_w[2]; // grown when dragging the lower divider up
|
||||
|
||||
if k == 0 && pane_top >= COLLAPSE_GROW {
|
||||
// Upper pane grown out → drop the bottom pane; the surviving {0,1} divider snaps to
|
||||
// where it was dropped.
|
||||
if let Some((tt, tc)) = op_r4(top, 3) {
|
||||
let to_w = collapse_2pane(from_w[0], from_w[1]);
|
||||
begin_anim(state, top, 3, from_w, tt, tc, to_w, 0.0, now);
|
||||
}
|
||||
} else if k == 1 && pane_bot >= COLLAPSE_GROW {
|
||||
// Bottom pane grown out → drop the top pane; surviving {1,2} divider snaps to drop.
|
||||
if let Some((tt, tc)) = op_r3(top, 3) {
|
||||
let to_w = collapse_2pane(from_w[1], from_w[2]);
|
||||
begin_anim(state, top, 3, from_w, tt, tc, to_w, 0.0, now);
|
||||
}
|
||||
} else if b <= COLLAPSE_LO {
|
||||
if let Some((tt, tc)) = op_r1(top, 3) {
|
||||
begin_anim(state, top, 3, from_w, tt, tc, even_arr(tc), 0.0, now);
|
||||
}
|
||||
} else if b >= COLLAPSE_HI {
|
||||
if let Some((tt, tc)) = op_r2(top, 3) {
|
||||
begin_anim(state, top, 3, from_w, tt, tc, even_arr(tc), 0.0, now);
|
||||
}
|
||||
} else {
|
||||
// Snap both dividers together: round the path parameter to the nearest preset.
|
||||
let (lo, hi) = path3_range(k);
|
||||
let s = s_from_boundary(k, b.clamp(lo, hi)).round().clamp(0.0, 2.0);
|
||||
let to_w = PRESETS_3[s as usize];
|
||||
begin_anim(state, top, 3, from_w, top, 3, to_w, 0.0, now);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 2-pane: group resize snapping to the nearest 2-pane preset, but releasing near an edge
|
||||
// collapses to a single fullscreen pane (the one that grew). It does NOT slide in the next pane —
|
||||
// that's the job of the top/bottom edge handles.
|
||||
let (bmin, bmax) = boundary_bounds(count, k);
|
||||
let from_w = to_arr(&weights_for_boundary(&nw, k, b.clamp(bmin, bmax)));
|
||||
if b <= COLLAPSE_LO {
|
||||
// Divider dragged to the top → the top pane is squeezed out; the bottom pane goes fullscreen.
|
||||
begin_anim(state, top, count, from_w, top + 1, 1, even_arr(1), 0.0, now);
|
||||
} else if b >= COLLAPSE_HI {
|
||||
// Divider dragged to the bottom → the bottom pane is squeezed out; the top pane goes fullscreen.
|
||||
begin_anim(state, top, count, from_w, top, 1, even_arr(1), 0.0, now);
|
||||
} else {
|
||||
let to_w = nearest_preset(&from_w, count);
|
||||
begin_anim(state, top, count, from_w, top, count, to_w, 0.0, now);
|
||||
}
|
||||
}
|
||||
|
||||
/// Given the two surviving panes' (unnormalized) sizes after a 3→2 collapse, snap to the nearest
|
||||
/// 2-pane preset by the first pane's proportion.
|
||||
fn collapse_2pane(a: f32, b: f32) -> [f32; 3] {
|
||||
let total = (a + b).max(1e-4);
|
||||
let p0 = a / total;
|
||||
nearest_preset(&[p0, 1.0 - p0, 0.0], 2)
|
||||
}
|
||||
|
||||
/// Switch to a new window config, easing from `from_*` to the new state over the snap duration.
|
||||
/// `start_p` back-dates the animation so it can continue an in-progress drag.
|
||||
fn begin_anim(
|
||||
state: &mut MobileState,
|
||||
from_top: usize,
|
||||
from_count: usize,
|
||||
from_w: [f32; 3],
|
||||
to_top: usize,
|
||||
to_count: usize,
|
||||
to_w: [f32; 3],
|
||||
start_p: f32,
|
||||
now: f64,
|
||||
) {
|
||||
state.window_top = to_top;
|
||||
state.window_count = to_count;
|
||||
state.weights = to_w;
|
||||
state.anim = Some(LayoutAnim {
|
||||
from_top,
|
||||
from_count,
|
||||
from_w,
|
||||
to_top,
|
||||
to_count,
|
||||
to_w,
|
||||
start: now - start_p as f64 * SNAP_ANIM_SECS,
|
||||
});
|
||||
}
|
||||
|
||||
/// Switch the visible window and reset to even pane sizing, easing the transition.
|
||||
fn set_window(state: &mut MobileState, top: usize, count: usize, now: f64) {
|
||||
let from_w = to_arr(&nweights(&state.weights, state.window_count));
|
||||
begin_anim(state, state.window_top, state.window_count, from_w, top, count, even_arr(count), 0.0, now);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Full-bleed hero surface rendering: maps a mobile surface to an existing pane and renders
|
||||
//! its content into a rect with no header/divider chrome. This is the de-chromed core of
|
||||
//! `render_pane` (main.rs) — see the get-or-create + `render_content` pattern there.
|
||||
|
||||
use eframe::egui;
|
||||
use lightningbeam_core::pane::PaneType;
|
||||
|
||||
use crate::panes::{NodePath, PaneInstance, PaneRenderer};
|
||||
use crate::RenderContext;
|
||||
|
||||
/// Render `pane_type` full-bleed into `rect`, reusing (or creating) the cached pane instance
|
||||
/// keyed by `path`. The pane clips its own drawing to `rect`, so no extra clipping is needed.
|
||||
pub fn render_surface_fullbleed(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
path: &NodePath,
|
||||
pane_type: PaneType,
|
||||
rc: &mut RenderContext,
|
||||
) {
|
||||
// Get-or-create the instance for this slot (recreate if the type changed).
|
||||
let needs_new = rc
|
||||
.pane_instances
|
||||
.get(path)
|
||||
.map(|inst| inst.pane_type() != pane_type)
|
||||
.unwrap_or(true);
|
||||
if needs_new {
|
||||
rc.pane_instances.insert(path.clone(), PaneInstance::new(pane_type));
|
||||
}
|
||||
|
||||
if let Some(inst) = rc.pane_instances.get_mut(path) {
|
||||
inst.render_content(ui, rect, path, &mut rc.shared);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
//! The mobile top bar: the project filename on the left, and on the right ⌕ (command palette) and
|
||||
//! ⋯ (overflow commands). Both open a modal sheet whose items dispatch `MenuAction`s (which
|
||||
//! `main.rs::handle_menu_action` already implements). Per the wireframe these are the
|
||||
//! "commands/destinations", as opposed to the omnibutton's "tools/objects".
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
use super::{icons, MobileState, Palette};
|
||||
use crate::menu::{MenuAction, MenuDef, MenuItemDef};
|
||||
use crate::RenderContext;
|
||||
|
||||
const BTN: f32 = 40.0;
|
||||
|
||||
/// Curated overflow (⋯) commands.
|
||||
fn overflow_items() -> [(&'static str, MenuAction); 9] {
|
||||
[
|
||||
("Save", MenuAction::Save),
|
||||
("Save As…", MenuAction::SaveAs),
|
||||
("Open File…", MenuAction::OpenFile),
|
||||
("New file…", MenuAction::NewFile),
|
||||
("Import…", MenuAction::Import),
|
||||
("Export…", MenuAction::Export),
|
||||
("Undo", MenuAction::Undo),
|
||||
("Redo", MenuAction::Redo),
|
||||
("Preferences", MenuAction::Preferences),
|
||||
]
|
||||
}
|
||||
|
||||
/// Flatten the whole menu tree into (path-label, action) for the command palette.
|
||||
fn flatten(defs: &'static [MenuDef], prefix: &str, out: &mut Vec<(String, MenuAction)>) {
|
||||
for d in defs {
|
||||
match d {
|
||||
MenuDef::Item(item) => out.push((format!("{prefix}{}", item.label), item.action)),
|
||||
MenuDef::Submenu { label, children } => {
|
||||
flatten(children, &format!("{prefix}{label} › "), out);
|
||||
}
|
||||
MenuDef::Separator => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn all_commands() -> Vec<(String, MenuAction)> {
|
||||
let mut v = Vec::new();
|
||||
flatten(MenuItemDef::menu_structure(), "", &mut v);
|
||||
v
|
||||
}
|
||||
|
||||
pub fn render(
|
||||
ui: &mut egui::Ui,
|
||||
bar: egui::Rect,
|
||||
full: egui::Rect,
|
||||
rc: &mut RenderContext,
|
||||
state: &mut MobileState,
|
||||
pal: &Palette,
|
||||
) {
|
||||
ui.painter().rect_filled(bar, 0.0, pal.header);
|
||||
ui.painter().hline(bar.x_range(), bar.bottom(), egui::Stroke::new(1.0, pal.line));
|
||||
|
||||
// Filename (or app name when unsaved).
|
||||
let name = rc
|
||||
.shared
|
||||
.container_path
|
||||
.as_ref()
|
||||
.and_then(|p| p.file_name())
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "Lightningbeam".to_string());
|
||||
ui.painter().text(
|
||||
egui::pos2(bar.left() + 14.0, bar.center().y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
name,
|
||||
egui::FontId::proportional(14.0),
|
||||
pal.text,
|
||||
);
|
||||
|
||||
// Right cluster: ⌕ (palette) then ⋯ (overflow).
|
||||
let overflow_rect = egui::Rect::from_min_size(egui::pos2(bar.right() - BTN, bar.top()), egui::vec2(BTN, bar.height()));
|
||||
let palette_rect = egui::Rect::from_min_size(egui::pos2(bar.right() - 2.0 * BTN, bar.top()), egui::vec2(BTN, bar.height()));
|
||||
|
||||
let sresp = ui.interact(palette_rect, ui.id().with("mobile_topbar_search"), egui::Sense::click());
|
||||
ui.painter().text(palette_rect.center(), egui::Align2::CENTER_CENTER, icons::SEARCH, icons::font(17.0),
|
||||
if sresp.hovered() || state.palette_open { pal.text } else { pal.text_dim });
|
||||
if sresp.clicked() {
|
||||
state.palette_open = !state.palette_open;
|
||||
state.overflow_open = false;
|
||||
state.palette_query.clear();
|
||||
}
|
||||
|
||||
let oresp = ui.interact(overflow_rect, ui.id().with("mobile_topbar_overflow"), egui::Sense::click());
|
||||
ui.painter().text(overflow_rect.center(), egui::Align2::CENTER_CENTER, icons::ELLIPSIS, icons::font(18.0),
|
||||
if oresp.hovered() || state.overflow_open { pal.text } else { pal.text_dim });
|
||||
if oresp.clicked() {
|
||||
state.overflow_open = !state.overflow_open;
|
||||
state.palette_open = false;
|
||||
}
|
||||
|
||||
if state.overflow_open {
|
||||
render_overflow(ui, full, rc, state, pal);
|
||||
} else if state.palette_open {
|
||||
render_palette(ui, full, rc, state, pal);
|
||||
}
|
||||
}
|
||||
|
||||
/// Landscape: the app bar folded into the middle of the top pane header — filename + ⌕ + ⋯ as a
|
||||
/// centered cluster (the pane's own grip/label sits to the left, its buttons to the right). No bar
|
||||
/// background or divider line; the header already drew them.
|
||||
pub fn render_inline(
|
||||
ui: &mut egui::Ui,
|
||||
header: egui::Rect,
|
||||
full: egui::Rect,
|
||||
rc: &mut RenderContext,
|
||||
state: &mut MobileState,
|
||||
pal: &Palette,
|
||||
) {
|
||||
let name = rc
|
||||
.shared
|
||||
.container_path
|
||||
.as_ref()
|
||||
.and_then(|p| p.file_name())
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "Lightningbeam".to_string());
|
||||
let btn = header.height().min(BTN);
|
||||
let gap = 6.0;
|
||||
// Reserve gutters so the cluster never overlaps the pane header's own grip/label (left) or its
|
||||
// fullscreen / node-toggle buttons (right).
|
||||
let left_gutter = 150.0;
|
||||
let right_gutter = 2.0 * BTN + 16.0;
|
||||
let span_left = header.left() + left_gutter;
|
||||
let span_right = (header.right() - right_gutter).max(span_left);
|
||||
let span_w = span_right - span_left;
|
||||
|
||||
// Filename elided to fit whatever's left after the two buttons.
|
||||
let max_name_w = (span_w - gap - 2.0 * btn).max(0.0);
|
||||
let galley = {
|
||||
let mut job =
|
||||
egui::text::LayoutJob::simple_singleline(name, egui::FontId::proportional(14.0), pal.text);
|
||||
job.wrap.max_width = max_name_w;
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
ui.painter().layout_job(job)
|
||||
};
|
||||
let name_w = galley.rect.width();
|
||||
let name_h = galley.rect.height();
|
||||
let cluster_w = name_w + gap + 2.0 * btn;
|
||||
// Center within the reserved span, then clamp so the right edge stays inside it.
|
||||
let x0 = (span_left + (span_w - cluster_w) / 2.0).clamp(span_left, (span_right - cluster_w).max(span_left));
|
||||
let cy = header.center().y;
|
||||
let bt = header.top() + (header.height() - btn) / 2.0;
|
||||
|
||||
ui.painter().galley(egui::pos2(x0, cy - name_h / 2.0), galley, pal.text);
|
||||
|
||||
let palette_rect = egui::Rect::from_min_size(egui::pos2(x0 + name_w + gap, bt), egui::vec2(btn, btn));
|
||||
let overflow_rect = egui::Rect::from_min_size(egui::pos2(palette_rect.right(), bt), egui::vec2(btn, btn));
|
||||
|
||||
let sresp = ui.interact(palette_rect, ui.id().with("mobile_topbar_search"), egui::Sense::click());
|
||||
ui.painter().text(palette_rect.center(), egui::Align2::CENTER_CENTER, icons::SEARCH, icons::font(17.0),
|
||||
if sresp.hovered() || state.palette_open { pal.text } else { pal.text_dim });
|
||||
if sresp.clicked() {
|
||||
state.palette_open = !state.palette_open;
|
||||
state.overflow_open = false;
|
||||
state.palette_query.clear();
|
||||
}
|
||||
|
||||
let oresp = ui.interact(overflow_rect, ui.id().with("mobile_topbar_overflow"), egui::Sense::click());
|
||||
ui.painter().text(overflow_rect.center(), egui::Align2::CENTER_CENTER, icons::ELLIPSIS, icons::font(18.0),
|
||||
if oresp.hovered() || state.overflow_open { pal.text } else { pal.text_dim });
|
||||
if oresp.clicked() {
|
||||
state.overflow_open = !state.overflow_open;
|
||||
state.palette_open = false;
|
||||
}
|
||||
|
||||
if state.overflow_open {
|
||||
render_overflow(ui, full, rc, state, pal);
|
||||
} else if state.palette_open {
|
||||
render_palette(ui, full, rc, state, pal);
|
||||
}
|
||||
}
|
||||
|
||||
/// Common modal scrim + panel. Returns (backdrop-tapped, panel inner rect).
|
||||
fn open_panel(ui: &mut egui::Ui, full: egui::Rect, id: &str, pal: &Palette) -> (bool, egui::Rect) {
|
||||
let scrim = ui.interact(full, ui.id().with(("mobile_topbar_scrim", id)), egui::Sense::click());
|
||||
ui.painter().rect_filled(full, 0.0, pal.scrim);
|
||||
let panel = egui::Rect::from_min_max(
|
||||
egui::pos2(full.left() + 16.0, full.top() + 44.0),
|
||||
egui::pos2(full.right() - 16.0, full.bottom() - 60.0),
|
||||
);
|
||||
ui.painter().rect_filled(panel, 14.0, pal.surface);
|
||||
ui.painter().rect_stroke(panel, 14.0, egui::Stroke::new(1.0, pal.line), egui::StrokeKind::Inside);
|
||||
(scrim.clicked(), panel)
|
||||
}
|
||||
|
||||
fn command_button(ui: &mut egui::Ui, r: egui::Rect, label: &str, key: (&str, usize), pal: &Palette) -> bool {
|
||||
let resp = ui.interact(r, ui.id().with(("mobile_cmd", key.0, key.1)), egui::Sense::click());
|
||||
ui.painter().rect_filled(r, 8.0, if resp.hovered() { pal.surface_alt } else { pal.surface });
|
||||
ui.painter().hline(r.x_range(), r.bottom(), egui::Stroke::new(1.0, pal.line));
|
||||
ui.painter().text(
|
||||
egui::pos2(r.left() + 14.0, r.center().y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
egui::FontId::proportional(13.0),
|
||||
pal.text,
|
||||
);
|
||||
resp.clicked()
|
||||
}
|
||||
|
||||
fn render_overflow(ui: &mut egui::Ui, full: egui::Rect, rc: &mut RenderContext, state: &mut MobileState, pal: &Palette) {
|
||||
let (backdrop, panel) = open_panel(ui, full, "overflow", pal);
|
||||
let mut close = backdrop;
|
||||
let items = overflow_items();
|
||||
let row_h = 44.0;
|
||||
let inner = panel.shrink(8.0);
|
||||
for (i, (label, action)) in items.iter().enumerate() {
|
||||
let r = egui::Rect::from_min_size(
|
||||
egui::pos2(inner.left(), inner.top() + i as f32 * row_h),
|
||||
egui::vec2(inner.width(), row_h),
|
||||
);
|
||||
if r.bottom() > inner.bottom() {
|
||||
break;
|
||||
}
|
||||
if command_button(ui, r, label, ("of", i), pal) {
|
||||
rc.shared.pending_menu_actions.push(*action);
|
||||
close = true;
|
||||
}
|
||||
}
|
||||
if close {
|
||||
state.overflow_open = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn render_palette(ui: &mut egui::Ui, full: egui::Rect, rc: &mut RenderContext, state: &mut MobileState, pal: &Palette) {
|
||||
let (backdrop, panel) = open_panel(ui, full, "palette", pal);
|
||||
let mut close = backdrop;
|
||||
let inner = panel.shrink(8.0);
|
||||
|
||||
// Search field (real egui widget).
|
||||
let field = egui::Rect::from_min_size(inner.min, egui::vec2(inner.width(), 30.0));
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(field).layout(egui::Layout::left_to_right(egui::Align::Center)));
|
||||
let te = child.add(
|
||||
egui::TextEdit::singleline(&mut state.palette_query)
|
||||
.hint_text("Search commands…")
|
||||
.desired_width(inner.width()),
|
||||
);
|
||||
// Focus the field only when it isn't already focused — re-requesting every frame would stomp
|
||||
// focus and prevent anything else in the panel from taking it.
|
||||
if !te.has_focus() {
|
||||
te.request_focus();
|
||||
}
|
||||
|
||||
// Filtered list.
|
||||
let q = state.palette_query.to_lowercase();
|
||||
let cmds = all_commands();
|
||||
let row_h = 38.0;
|
||||
let list_top = inner.top() + 38.0;
|
||||
let mut y = list_top;
|
||||
for (i, (label, action)) in cmds.iter().enumerate() {
|
||||
if !q.is_empty() && !label.to_lowercase().contains(&q) {
|
||||
continue;
|
||||
}
|
||||
let r = egui::Rect::from_min_size(egui::pos2(inner.left(), y), egui::vec2(inner.width(), row_h));
|
||||
if r.bottom() > inner.bottom() {
|
||||
break;
|
||||
}
|
||||
if command_button(ui, r, label, ("pal", i), pal) {
|
||||
rc.shared.pending_menu_actions.push(*action);
|
||||
close = true;
|
||||
}
|
||||
y += row_h;
|
||||
}
|
||||
if close {
|
||||
state.palette_open = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! The transport "floor": the always-present bottom bar with play/pause, the timecode, and a
|
||||
//! project scrub. Wired to the audio controller exactly like `TimelinePane`'s header.
|
||||
|
||||
use eframe::egui;
|
||||
|
||||
use super::{icons, Palette};
|
||||
use crate::panes::SharedPaneState;
|
||||
|
||||
pub fn render(ui: &mut egui::Ui, rect: egui::Rect, shared: &mut SharedPaneState, pal: &Palette) {
|
||||
let painter = ui.painter_at(rect);
|
||||
painter.rect_filled(rect, 0.0, pal.surface);
|
||||
painter.hline(rect.x_range(), rect.top(), egui::Stroke::new(1.0, pal.line));
|
||||
|
||||
let cy = rect.center().y;
|
||||
|
||||
// --- Play / pause button (circle on the left) ---
|
||||
let btn_r = 18.0;
|
||||
let btn_center = egui::pos2(rect.left() + 20.0 + btn_r, cy);
|
||||
let btn_rect = egui::Rect::from_center_size(btn_center, egui::vec2(btn_r * 2.0, btn_r * 2.0));
|
||||
let btn_resp = ui.interact(btn_rect, ui.id().with("mobile_transport_play"), egui::Sense::click());
|
||||
painter.circle_filled(btn_center, btn_r, pal.accent);
|
||||
let glyph = if *shared.is_playing { icons::PAUSE } else { icons::PLAY };
|
||||
painter.text(
|
||||
btn_center,
|
||||
egui::Align2::CENTER_CENTER,
|
||||
glyph,
|
||||
icons::font(16.0),
|
||||
pal.on_accent,
|
||||
);
|
||||
if btn_resp.clicked() {
|
||||
*shared.is_playing = !*shared.is_playing;
|
||||
if let Some(controller_arc) = shared.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
if *shared.is_playing {
|
||||
controller.seek(*shared.playback_time);
|
||||
controller.play();
|
||||
} else {
|
||||
controller.pause();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Playhead readout: format follows the project's TimelineMode (set at creation by type). ---
|
||||
let t = *shared.playback_time;
|
||||
let tc = {
|
||||
use lightningbeam_core::document::TimelineMode;
|
||||
let doc = shared.action_executor.document();
|
||||
match doc.timeline_mode {
|
||||
TimelineMode::Measures => {
|
||||
let pos = lightningbeam_core::beat_time::time_to_measure(t, doc.tempo_map(), &doc.time_signature);
|
||||
format!("{}.{}.{:02}", pos.measure, pos.beat, pos.tick / 10)
|
||||
}
|
||||
TimelineMode::Frames => format_timecode(t, doc.framerate.max(1.0)),
|
||||
TimelineMode::Seconds => {
|
||||
let total = t.max(0.0);
|
||||
let m = (total / 60.0).floor() as u32;
|
||||
format!("{:02}:{:06.3}", m, total % 60.0)
|
||||
}
|
||||
}
|
||||
};
|
||||
let tc_left = btn_rect.right() + 12.0;
|
||||
painter.text(
|
||||
egui::pos2(tc_left, cy),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
&tc,
|
||||
egui::FontId::monospace(13.0),
|
||||
pal.text,
|
||||
);
|
||||
let tc_width = 78.0;
|
||||
|
||||
// --- Project scrub (fills the remaining width) ---
|
||||
let duration = shared.action_executor.document().duration.max(1.0);
|
||||
let scrub_left = tc_left + tc_width;
|
||||
let scrub_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(scrub_left, cy - 3.0),
|
||||
egui::pos2(rect.right() - 14.0, cy + 3.0),
|
||||
);
|
||||
let scrub_resp = ui.interact(
|
||||
scrub_rect.expand2(egui::vec2(0.0, 12.0)),
|
||||
ui.id().with("mobile_transport_scrub"),
|
||||
egui::Sense::click_and_drag(),
|
||||
);
|
||||
painter.rect_filled(scrub_rect, 3.0, pal.line);
|
||||
let frac = (*shared.playback_time / duration).clamp(0.0, 1.0) as f32;
|
||||
let filled = egui::Rect::from_min_max(
|
||||
scrub_rect.min,
|
||||
egui::pos2(scrub_rect.left() + scrub_rect.width() * frac, scrub_rect.bottom()),
|
||||
);
|
||||
painter.rect_filled(filled, 3.0, pal.accent.gamma_multiply(0.5));
|
||||
let head_x = scrub_rect.left() + scrub_rect.width() * frac;
|
||||
painter.vline(
|
||||
head_x,
|
||||
(scrub_rect.top() - 4.0)..=(scrub_rect.bottom() + 4.0),
|
||||
egui::Stroke::new(2.0, pal.accent),
|
||||
);
|
||||
|
||||
if (scrub_resp.dragged() || scrub_resp.clicked()) && scrub_rect.width() > 0.0 {
|
||||
if let Some(pos) = scrub_resp.interact_pointer_pos() {
|
||||
let f = ((pos.x - scrub_rect.left()) / scrub_rect.width()).clamp(0.0, 1.0) as f64;
|
||||
let new_time = f * duration;
|
||||
*shared.playback_time = new_time;
|
||||
if let Some(controller_arc) = shared.audio_controller {
|
||||
let mut controller = controller_arc.lock().unwrap();
|
||||
controller.seek(new_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn format_timecode(seconds: f64, fps: f64) -> String {
|
||||
let total = seconds.max(0.0);
|
||||
let minutes = (total / 60.0).floor() as u32;
|
||||
let secs = (total % 60.0).floor() as u32;
|
||||
let frames = ((total - total.floor()) * fps).floor() as u32;
|
||||
format!("{:02}:{:02}:{:02}", minutes, secs, frames)
|
||||
}
|
||||
@@ -32,6 +32,11 @@ pub fn notify_export_complete(output_path: &Path) {
|
||||
|
||||
/// Show a desktop notification for an export error (fire-and-forget).
|
||||
pub fn notify_export_error(error_message: &str) {
|
||||
notify_error("Export Failed", error_message);
|
||||
}
|
||||
|
||||
/// Show a desktop error notification with a custom title (fire-and-forget).
|
||||
pub fn notify_error(title: &'static str, error_message: &str) {
|
||||
// Truncate very long error messages (on a char boundary).
|
||||
let truncated = if error_message.chars().count() > 100 {
|
||||
let prefix: String = error_message.chars().take(97).collect();
|
||||
@@ -42,7 +47,7 @@ pub fn notify_export_error(error_message: &str) {
|
||||
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) = Notification::new()
|
||||
.summary("Export Failed")
|
||||
.summary(title)
|
||||
.body(&truncated)
|
||||
.icon("dialog-error") // Standard error icon
|
||||
.timeout(10000) // 10 seconds for errors (longer to read)
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! NV12 → linear-RGB blit: composites a hardware-decoded video frame (two wgpu plane textures,
|
||||
//! Y = R8Unorm + CbCr = Rg8Unorm) directly into the Rgba16Float HDR layer, with no CPU upload.
|
||||
//! The colour math mirrors the software path (BT.709 → sRGB-encoded → linear) so hardware- and
|
||||
//! software-decoded video look identical. See `panes/shaders/nv12_blit.wgsl`.
|
||||
|
||||
use crate::gpu_brush::BlitTransform;
|
||||
use lightningbeam_core::video::{VideoPrimaries, VideoTransfer};
|
||||
|
||||
/// Uniform: the `viewport_uv → frame_uv` affine (same packing as [`BlitTransform`]), the Y'CbCr→RGB
|
||||
/// matrix coefficients, and a flags vec4. 80 bytes (48 matrix + 16 coeffs + 16 flags).
|
||||
/// `flags`: `[full_range, transfer (0 gamma / 1 PQ / 2 HLG), primaries (0 BT.709 / 1 BT.2020), pad]`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
struct Nv12Params {
|
||||
transform: BlitTransform,
|
||||
coeffs: [f32; 4],
|
||||
flags: [u32; 4],
|
||||
}
|
||||
|
||||
pub struct Nv12BlitPipeline {
|
||||
pipeline: wgpu::RenderPipeline,
|
||||
bg_layout: wgpu::BindGroupLayout,
|
||||
sampler: wgpu::Sampler,
|
||||
}
|
||||
|
||||
impl Nv12BlitPipeline {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("nv12_blit_shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
include_str!("panes/shaders/nv12_blit.wgsl").into(),
|
||||
),
|
||||
});
|
||||
|
||||
let tex_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
};
|
||||
|
||||
let bg_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("nv12_blit_bgl"),
|
||||
entries: &[
|
||||
tex_entry(0), // Y plane (R8Unorm)
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 2,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
tex_entry(3), // CbCr plane (Rg8Unorm)
|
||||
],
|
||||
});
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("nv12_blit_pl"),
|
||||
bind_group_layouts: &[&bg_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
|
||||
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("nv12_blit_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some("fs_main"),
|
||||
targets: &[Some(wgpu::ColorTargetState {
|
||||
format: wgpu::TextureFormat::Rgba16Float,
|
||||
blend: None,
|
||||
write_mask: wgpu::ColorWrites::ALL,
|
||||
})],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleStrip,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: wgpu::MultisampleState::default(),
|
||||
multiview: None,
|
||||
cache: None,
|
||||
});
|
||||
|
||||
// Bilinear: the frame is scaled to the output size; nearest would look blocky.
|
||||
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
|
||||
label: Some("nv12_blit_sampler"),
|
||||
address_mode_u: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_v: wgpu::AddressMode::ClampToEdge,
|
||||
address_mode_w: wgpu::AddressMode::ClampToEdge,
|
||||
mag_filter: wgpu::FilterMode::Linear,
|
||||
min_filter: wgpu::FilterMode::Linear,
|
||||
mipmap_filter: wgpu::FilterMode::Linear,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
Self { pipeline, bg_layout, sampler }
|
||||
}
|
||||
|
||||
/// Convert + blit the NV12 frame into `target_view` (Rgba16Float, cleared to transparent),
|
||||
/// positioned by `transform` (built like the RGBA video path's `BlitTransform`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn blit(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
queue: &wgpu::Queue,
|
||||
y_view: &wgpu::TextureView,
|
||||
uv_view: &wgpu::TextureView,
|
||||
target_view: &wgpu::TextureView,
|
||||
transform: &BlitTransform,
|
||||
full_range: bool,
|
||||
coeffs: [f32; 4],
|
||||
transfer: VideoTransfer,
|
||||
primaries: VideoPrimaries,
|
||||
) {
|
||||
let transfer_code = match transfer {
|
||||
VideoTransfer::Gamma => 0,
|
||||
VideoTransfer::Pq => 1,
|
||||
VideoTransfer::Hlg => 2,
|
||||
};
|
||||
let primaries_code = match primaries {
|
||||
VideoPrimaries::Bt709 => 0,
|
||||
VideoPrimaries::Bt2020 => 1,
|
||||
};
|
||||
let params = Nv12Params {
|
||||
transform: *transform,
|
||||
coeffs,
|
||||
flags: [full_range as u32, transfer_code, primaries_code, 0],
|
||||
};
|
||||
let param_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("nv12_blit_params"),
|
||||
size: std::mem::size_of::<Nv12Params>() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
queue.write_buffer(¶m_buf, 0, bytemuck::bytes_of(¶ms));
|
||||
|
||||
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("nv12_blit_bg"),
|
||||
layout: &self.bg_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(y_view) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },
|
||||
wgpu::BindGroupEntry { binding: 2, resource: param_buf.as_entire_binding() },
|
||||
wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(uv_view) },
|
||||
],
|
||||
});
|
||||
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("nv12_blit_encoder"),
|
||||
});
|
||||
{
|
||||
let mut rp = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("nv12_blit_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: target_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
occlusion_query_set: None,
|
||||
timestamp_writes: None,
|
||||
});
|
||||
rp.set_pipeline(&self.pipeline);
|
||||
rp.set_bind_group(0, &bg, &[]);
|
||||
rp.draw(0..4, 0..1);
|
||||
}
|
||||
queue.submit(Some(encoder.finish()));
|
||||
}
|
||||
}
|
||||
@@ -316,7 +316,10 @@ fn generate_video_thumbnail(
|
||||
|
||||
let frame = {
|
||||
let mut video_mgr = video_manager.lock().ok()?;
|
||||
video_mgr.get_frame(clip_id, timestamp)?
|
||||
// Small CPU frame for the asset thumbnail (capped to native, aspect preserved). Force CPU:
|
||||
// the render-pass hardware flag may be on, but the thumbnail needs RGBA bytes (a GPU frame
|
||||
// has empty rgba_data → an all-black thumbnail).
|
||||
video_mgr.get_frame_cpu(clip_id, timestamp, THUMBNAIL_SIZE, THUMBNAIL_SIZE)?
|
||||
};
|
||||
|
||||
let src_width = frame.width as usize;
|
||||
@@ -1289,6 +1292,9 @@ impl AssetLibraryPane {
|
||||
lightningbeam_core::layer::AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have their own clip instances
|
||||
}
|
||||
lightningbeam_core::layer::AnyLayer::Text(_) => {
|
||||
// Text layers don't have their own clip instances
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
|
||||
@@ -44,10 +44,23 @@ pub struct InfopanelPane {
|
||||
selected_tool_gradient_stop: Option<usize>,
|
||||
/// FPS value captured when a drag/focus-in starts (for single-undo-action on commit)
|
||||
fps_drag_start: Option<f64>,
|
||||
/// In-progress layer-name edit buffer, keyed by the layer being edited.
|
||||
layer_name_edit: Option<(Uuid, String)>,
|
||||
/// Layer opacity/volume captured when a slider drag starts (single-undo on commit).
|
||||
layer_opacity_drag_start: Option<f64>,
|
||||
layer_volume_drag_start: Option<f64>,
|
||||
/// Resize mode for the active raster layer's "to document size" action (scale vs canvas).
|
||||
raster_resize_mode: lightningbeam_core::raster_layer::RasterResizeMode,
|
||||
/// Font families already registered into egui for the family-picker previews
|
||||
/// (rendered each entry in its own font), so we only load each once.
|
||||
registered_preview_fonts: std::collections::HashSet<String>,
|
||||
}
|
||||
|
||||
impl InfopanelPane {
|
||||
pub fn new() -> Self {
|
||||
// Kick off background loading of the font-picker fonts at startup so the dropdown
|
||||
// is ready without a hitch by the time the user opens it.
|
||||
lightningbeam_core::fonts::start_preload();
|
||||
let presets = bundled_brushes();
|
||||
let default_eraser_idx = presets.iter().position(|p| p.name == "Brush");
|
||||
Self {
|
||||
@@ -61,8 +74,30 @@ impl InfopanelPane {
|
||||
selected_shape_gradient_stop: None,
|
||||
selected_tool_gradient_stop: None,
|
||||
fps_drag_start: None,
|
||||
layer_name_edit: None,
|
||||
layer_opacity_drag_start: None,
|
||||
layer_volume_drag_start: None,
|
||||
raster_resize_mode: lightningbeam_core::raster_layer::RasterResizeMode::Scale,
|
||||
registered_preview_fonts: std::collections::HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Register pre-loaded `bytes` for `family` into egui under `FontFamily::Name(family)`
|
||||
/// so a label can be rendered in that font. Cheap (no font IO); the add is idempotent
|
||||
/// and batched into one atlas rebuild at frame end, so the preview appears next frame.
|
||||
fn register_font_bytes(&mut self, ctx: &egui::Context, family: &str, bytes: Vec<u8>) {
|
||||
if family.is_empty() || !self.registered_preview_fonts.insert(family.to_string()) {
|
||||
return;
|
||||
}
|
||||
ctx.add_font(egui::epaint::text::FontInsert::new(
|
||||
family,
|
||||
egui::FontData::from_owned(bytes),
|
||||
vec![egui::epaint::text::InsertFontFamily {
|
||||
family: egui::FontFamily::Name(family.into()),
|
||||
priority: egui::epaint::text::FontPriority::Highest,
|
||||
}],
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Aggregated info about the current DCEL selection
|
||||
@@ -980,10 +1015,10 @@ impl InfopanelPane {
|
||||
|
||||
// Extract all needed values up front, then drop the borrow before closures
|
||||
// that need mutable access to shared or self.
|
||||
let (mut width, mut height, mut duration, mut framerate, layer_count, background_color) = {
|
||||
let (mut width, mut height, mut duration, mut framerate, layer_count, background_color, mut hdr_mode) = {
|
||||
let document = shared.action_executor.document();
|
||||
(document.width, document.height, document.duration, document.framerate,
|
||||
document.root.children.len(), document.background_color)
|
||||
document.root.children.len(), document.background_color, document.hdr_output_mode)
|
||||
};
|
||||
|
||||
// Canvas width
|
||||
@@ -1087,6 +1122,23 @@ impl InfopanelPane {
|
||||
}
|
||||
});
|
||||
|
||||
// HDR output mode (how super-white video highlights map to SDR output)
|
||||
ui.horizontal(|ui| {
|
||||
use lightningbeam_core::document::HdrOutputMode;
|
||||
ui.label("HDR output:");
|
||||
egui::ComboBox::from_id_salt(("hdr_output_mode", path))
|
||||
.selected_text(hdr_mode.name())
|
||||
.show_ui(ui, |ui| {
|
||||
let mut changed = false;
|
||||
changed |= ui.selectable_value(&mut hdr_mode, HdrOutputMode::Clip, HdrOutputMode::Clip.name()).changed();
|
||||
changed |= ui.selectable_value(&mut hdr_mode, HdrOutputMode::HighlightRolloff, HdrOutputMode::HighlightRolloff.name()).changed();
|
||||
if changed {
|
||||
let action = SetDocumentPropertiesAction::set_hdr_output_mode(hdr_mode);
|
||||
shared.pending_actions.push(Box::new(action));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Layer count (read-only)
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Layers:");
|
||||
@@ -1121,8 +1173,9 @@ impl InfopanelPane {
|
||||
}
|
||||
|
||||
/// Render layer info section
|
||||
fn render_layer_section(&self, ui: &mut Ui, path: &NodePath, shared: &SharedPaneState, layer_ids: &[Uuid]) {
|
||||
let document = shared.action_executor.document();
|
||||
fn render_layer_section(&mut self, ui: &mut Ui, path: &NodePath, shared: &mut SharedPaneState, layer_ids: &[Uuid]) {
|
||||
use lightningbeam_core::actions::{set_layer_properties::LayerProperty, SetLayerPropertiesAction};
|
||||
use lightningbeam_core::layer::AudioLayerType;
|
||||
|
||||
egui::CollapsingHeader::new("Layer")
|
||||
.id_salt(("layer_info", path))
|
||||
@@ -1130,56 +1183,384 @@ impl InfopanelPane {
|
||||
.show(ui, |ui| {
|
||||
ui.add_space(4.0);
|
||||
|
||||
if layer_ids.len() == 1 {
|
||||
if let Some(layer) = document.get_layer(&layer_ids[0]) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Name:");
|
||||
ui.label(layer.name());
|
||||
});
|
||||
if layer_ids.len() != 1 {
|
||||
ui.label(format!("{} layers selected", layer_ids.len()));
|
||||
ui.add_space(4.0);
|
||||
return;
|
||||
}
|
||||
let layer_id = layer_ids[0];
|
||||
|
||||
// Snapshot the current values, then drop the document borrow before mutating shared.
|
||||
let Some((type_name, is_audio, name, opacity, volume, muted, soloed, locked)) = ({
|
||||
let document = shared.action_executor.document();
|
||||
document.get_layer(&layer_id).map(|layer| {
|
||||
let type_name = match layer {
|
||||
AnyLayer::Vector(_) => "Vector",
|
||||
AnyLayer::Audio(a) => match a.audio_layer_type {
|
||||
lightningbeam_core::layer::AudioLayerType::Midi => "MIDI",
|
||||
lightningbeam_core::layer::AudioLayerType::Sampled => "Audio",
|
||||
AudioLayerType::Midi => "MIDI",
|
||||
AudioLayerType::Sampled => "Audio",
|
||||
},
|
||||
AnyLayer::Video(_) => "Video",
|
||||
AnyLayer::Effect(_) => "Effect",
|
||||
AnyLayer::Group(_) => "Group",
|
||||
AnyLayer::Raster(_) => "Raster",
|
||||
AnyLayer::Text(_) => "Text",
|
||||
};
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Type:");
|
||||
ui.label(type_name);
|
||||
});
|
||||
(
|
||||
type_name,
|
||||
matches!(layer, AnyLayer::Audio(_)),
|
||||
layer.name().to_string(),
|
||||
layer.opacity(),
|
||||
layer.volume(),
|
||||
layer.muted(),
|
||||
layer.soloed(),
|
||||
layer.locked(),
|
||||
)
|
||||
})
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Opacity:");
|
||||
ui.label(format!("{:.0}%", layer.opacity() * 100.0));
|
||||
});
|
||||
|
||||
if matches!(layer, AnyLayer::Audio(_)) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Volume:");
|
||||
ui.label(format!("{:.0}%", layer.volume() * 100.0));
|
||||
});
|
||||
}
|
||||
|
||||
if layer.muted() {
|
||||
ui.label("Muted");
|
||||
}
|
||||
if layer.locked() {
|
||||
ui.label("Locked");
|
||||
// Name (editable; commits on Enter / focus loss).
|
||||
if self.layer_name_edit.as_ref().map(|(id, _)| *id) != Some(layer_id) {
|
||||
self.layer_name_edit = Some((layer_id, name.clone()));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Name:");
|
||||
let buf = &mut self.layer_name_edit.as_mut().unwrap().1;
|
||||
let resp = ui.text_edit_singleline(buf);
|
||||
let commit = resp.lost_focus()
|
||||
&& (ui.input(|i| i.key_pressed(egui::Key::Enter)) || !resp.has_focus());
|
||||
if commit {
|
||||
let new_name = buf.trim().to_string();
|
||||
if !new_name.is_empty() && new_name != name {
|
||||
shared.pending_actions.push(Box::new(SetLayerPropertiesAction::new(
|
||||
layer_id,
|
||||
LayerProperty::Name(new_name),
|
||||
)));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ui.label(format!("{} layers selected", layer_ids.len()));
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Type:");
|
||||
ui.label(type_name);
|
||||
});
|
||||
|
||||
// Opacity slider (single-undo: live-preview while dragging, commit on release).
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Opacity:");
|
||||
let mut op = opacity;
|
||||
let r = ui.add(egui::Slider::new(&mut op, 0.0..=1.0).show_value(false));
|
||||
ui.label(format!("{:.0}%", op * 100.0));
|
||||
if (r.drag_started() || r.gained_focus()) && self.layer_opacity_drag_start.is_none() {
|
||||
self.layer_opacity_drag_start = Some(opacity);
|
||||
}
|
||||
if r.changed() {
|
||||
if let Some(l) = shared.action_executor.document_mut().get_layer_mut(&layer_id) {
|
||||
l.set_opacity(op);
|
||||
}
|
||||
}
|
||||
if r.drag_stopped() || r.lost_focus() {
|
||||
if let Some(start) = self.layer_opacity_drag_start.take() {
|
||||
if (start - op).abs() > 1e-6 {
|
||||
if let Some(l) = shared.action_executor.document_mut().get_layer_mut(&layer_id) {
|
||||
l.set_opacity(start); // revert so the action owns the change
|
||||
}
|
||||
shared.pending_actions.push(Box::new(SetLayerPropertiesAction::new(
|
||||
layer_id,
|
||||
LayerProperty::Opacity(op),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if is_audio {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Volume:");
|
||||
let mut vol = volume;
|
||||
let r = ui.add(egui::Slider::new(&mut vol, 0.0..=1.0).show_value(false));
|
||||
ui.label(format!("{:.0}%", vol * 100.0));
|
||||
if (r.drag_started() || r.gained_focus()) && self.layer_volume_drag_start.is_none() {
|
||||
self.layer_volume_drag_start = Some(volume);
|
||||
}
|
||||
if r.changed() {
|
||||
if let Some(l) = shared.action_executor.document_mut().get_layer_mut(&layer_id) {
|
||||
l.set_volume(vol);
|
||||
}
|
||||
}
|
||||
if r.drag_stopped() || r.lost_focus() {
|
||||
if let Some(start) = self.layer_volume_drag_start.take() {
|
||||
if (start - vol).abs() > 1e-6 {
|
||||
if let Some(l) = shared.action_executor.document_mut().get_layer_mut(&layer_id) {
|
||||
l.set_volume(start);
|
||||
}
|
||||
shared.pending_actions.push(Box::new(SetLayerPropertiesAction::new(
|
||||
layer_id,
|
||||
LayerProperty::Volume(vol),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Toggles: mute / solo (audio) / lock.
|
||||
ui.horizontal(|ui| {
|
||||
if is_audio {
|
||||
if ui.selectable_label(muted, "Mute").clicked() {
|
||||
shared.pending_actions.push(Box::new(SetLayerPropertiesAction::new(
|
||||
layer_id,
|
||||
LayerProperty::Muted(!muted),
|
||||
)));
|
||||
}
|
||||
if ui.selectable_label(soloed, "Solo").clicked() {
|
||||
shared.pending_actions.push(Box::new(SetLayerPropertiesAction::new(
|
||||
layer_id,
|
||||
LayerProperty::Soloed(!soloed),
|
||||
)));
|
||||
}
|
||||
}
|
||||
if ui.selectable_label(locked, "Lock").clicked() {
|
||||
shared.pending_actions.push(Box::new(SetLayerPropertiesAction::new(
|
||||
layer_id,
|
||||
LayerProperty::Locked(!locked),
|
||||
)));
|
||||
}
|
||||
});
|
||||
|
||||
ui.add_space(4.0);
|
||||
});
|
||||
}
|
||||
|
||||
/// Render a raster-layer section: shows the active keyframe's canvas dimensions and, when they
|
||||
/// differ from the document, a Scale/Expand-Crop mode toggle + a "Layer to document size" button.
|
||||
/// Driven by the *active* layer (not selection focus), since painting doesn't focus the layer.
|
||||
fn render_raster_layer_section(&mut self, ui: &mut Ui, path: &NodePath, shared: &mut SharedPaneState, layer_id: Uuid) {
|
||||
use lightningbeam_core::raster_layer::RasterResizeMode;
|
||||
|
||||
// Pull the values, then drop the document borrow before mutating `shared`.
|
||||
let time = *shared.playback_time;
|
||||
let dims = {
|
||||
let document = shared.action_executor.document();
|
||||
match document.get_layer(&layer_id) {
|
||||
Some(AnyLayer::Raster(rl)) => rl
|
||||
.keyframe_at(time)
|
||||
.map(|kf| (kf.width, kf.height, document.width as u32, document.height as u32)),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let Some((kf_w, kf_h, doc_w, doc_h)) = dims else { return };
|
||||
|
||||
egui::CollapsingHeader::new("Raster Layer")
|
||||
.id_salt(("raster_layer", path))
|
||||
.default_open(true)
|
||||
.show(ui, |ui| {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Size:");
|
||||
ui.label(format!("{} × {}", kf_w, kf_h));
|
||||
});
|
||||
|
||||
if kf_w != doc_w || kf_h != doc_h {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Mode:");
|
||||
ui.selectable_value(&mut self.raster_resize_mode, RasterResizeMode::Scale, "Scale");
|
||||
ui.selectable_value(&mut self.raster_resize_mode, RasterResizeMode::Canvas, "Expand/Crop");
|
||||
});
|
||||
if ui.button(format!("Layer to document size ({} × {})", doc_w, doc_h)).clicked() {
|
||||
let store = lightningbeam_core::raster_store::RasterStore::new(shared.container_path.clone());
|
||||
let action = lightningbeam_core::actions::ResizeRasterLayerAction::new(
|
||||
layer_id, doc_w, doc_h, self.raster_resize_mode, store,
|
||||
);
|
||||
shared.pending_actions.push(Box::new(action));
|
||||
}
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
});
|
||||
}
|
||||
|
||||
/// Render a text-layer section: edit the text content, font, size, color,
|
||||
/// alignment, and box size of the active text layer. Driven by the *active*
|
||||
/// layer so it appears whenever a text layer is selected.
|
||||
fn render_text_layer_section(&mut self, ui: &mut Ui, path: &NodePath, shared: &mut SharedPaneState, layer_id: Uuid) {
|
||||
use lightningbeam_core::text_layer::TextAlign;
|
||||
use lightningbeam_core::actions::{ResizeTextBoxAction, SetTextContentAction};
|
||||
|
||||
// Snapshot current values, then drop the document borrow before mutating shared.
|
||||
let snapshot = {
|
||||
let document = shared.action_executor.document();
|
||||
match document.get_layer(&layer_id) {
|
||||
Some(AnyLayer::Text(tl)) => {
|
||||
Some((tl.content.clone(), tl.box_origin, tl.box_width, tl.box_height))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
let Some((content0, origin, w0, h0)) = snapshot else { return };
|
||||
|
||||
// Families egui has actually bound (added fonts take effect next frame). Using an
|
||||
// unbound `FontFamily::Name` panics, so only preview-render families in this set.
|
||||
let bound_families: std::collections::HashSet<egui::FontFamily> =
|
||||
ui.ctx().fonts(|f| f.families().into_iter().collect());
|
||||
// Set when the font dropdown popup is open this frame (its closure only runs then),
|
||||
// so we can synchronously finish loading any not-yet-preloaded fonts the user sees.
|
||||
let mut dropdown_open = false;
|
||||
|
||||
egui::CollapsingHeader::new("Text")
|
||||
.id_salt(("text_layer", path))
|
||||
.default_open(true)
|
||||
.show(ui, |ui| {
|
||||
ui.add_space(4.0);
|
||||
let mut content = content0.clone();
|
||||
let mut content_changed = false;
|
||||
|
||||
ui.label("Text:");
|
||||
if ui
|
||||
.add(egui::TextEdit::multiline(&mut content.text).desired_rows(2).desired_width(f32::INFINITY))
|
||||
.changed()
|
||||
{
|
||||
content_changed = true;
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Size:");
|
||||
if ui
|
||||
.add(egui::DragValue::new(&mut content.font_size).range(1.0..=2000.0).speed(0.5))
|
||||
.changed()
|
||||
{
|
||||
content_changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Color:");
|
||||
// content.color is sRGB-encoded RGBA in 0..1 (matches peniko Color::new).
|
||||
let mut col = egui::Color32::from_rgba_unmultiplied(
|
||||
(content.color[0] * 255.0).round() as u8,
|
||||
(content.color[1] * 255.0).round() as u8,
|
||||
(content.color[2] * 255.0).round() as u8,
|
||||
(content.color[3] * 255.0).round() as u8,
|
||||
);
|
||||
if ui.color_edit_button_srgba(&mut col).changed() {
|
||||
content.color = [
|
||||
col.r() as f32 / 255.0,
|
||||
col.g() as f32 / 255.0,
|
||||
col.b() as f32 / 255.0,
|
||||
col.a() as f32 / 255.0,
|
||||
];
|
||||
content_changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Align:");
|
||||
for (label, a) in [("L", TextAlign::Left), ("C", TextAlign::Center), ("R", TextAlign::Right), ("J", TextAlign::Justify)] {
|
||||
if ui.selectable_label(content.align == a, label).clicked() {
|
||||
content.align = a;
|
||||
content_changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Font family picker (bundled families first, then system; embedded fonts
|
||||
// register under their own names on load).
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Font:");
|
||||
let current_label = if content.font_family.is_empty() {
|
||||
"(Default)".to_string()
|
||||
} else {
|
||||
content.font_family.clone()
|
||||
};
|
||||
egui::ComboBox::from_id_salt(("text_font", path))
|
||||
.selected_text(current_label)
|
||||
.show_ui(ui, |ui| {
|
||||
dropdown_open = true;
|
||||
if ui.selectable_label(content.font_family.is_empty(), "(Default)").clicked() {
|
||||
content.font_family.clear();
|
||||
content_changed = true;
|
||||
}
|
||||
// The popup closure only runs while the dropdown is open, so each
|
||||
// entry is rendered in its own font and queued for registration.
|
||||
for fam in lightningbeam_core::fonts::families() {
|
||||
let named = egui::FontFamily::Name(fam.as_str().into());
|
||||
// Render in its own font only once egui has bound it; otherwise
|
||||
// plain (and queue it for registration so it previews next frame).
|
||||
let label = if bound_families.contains(&named) {
|
||||
egui::RichText::new(&fam).family(named)
|
||||
} else {
|
||||
egui::RichText::new(&fam)
|
||||
};
|
||||
if ui.selectable_label(content.font_family == fam, label).clicked() {
|
||||
content.font_family = fam.clone();
|
||||
content_changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
// Missing-font indicator.
|
||||
if !content.font_family.is_empty()
|
||||
&& !lightningbeam_core::fonts::family_available(&content.font_family)
|
||||
{
|
||||
ui.colored_label(egui::Color32::from_rgb(230, 160, 60), "⚠ missing");
|
||||
}
|
||||
});
|
||||
|
||||
// Box size.
|
||||
let mut bw = w0;
|
||||
let mut bh = h0;
|
||||
let mut box_changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label("Box:");
|
||||
if ui.add(egui::DragValue::new(&mut bw).range(1.0..=100000.0).speed(1.0)).changed() {
|
||||
box_changed = true;
|
||||
}
|
||||
ui.label("×");
|
||||
if ui.add(egui::DragValue::new(&mut bh).range(1.0..=100000.0).speed(1.0)).changed() {
|
||||
box_changed = true;
|
||||
}
|
||||
});
|
||||
|
||||
ui.add_space(4.0);
|
||||
|
||||
if content_changed {
|
||||
shared.pending_actions.push(Box::new(SetTextContentAction::new(layer_id, content)));
|
||||
}
|
||||
if box_changed {
|
||||
shared.pending_actions.push(Box::new(ResizeTextBoxAction::new(layer_id, origin, bw, bh)));
|
||||
}
|
||||
});
|
||||
|
||||
// Register fonts the background preloader has finished (cheap: bytes already loaded),
|
||||
// a few per frame so each atlas rebuild stays small. Only fall back to synchronous
|
||||
// loading for families the user is actively viewing in the open dropdown that the
|
||||
// background hasn't reached yet. Repaint while there's more to do or the preloader
|
||||
// is still running, so registration keeps flowing without input.
|
||||
let ctx = ui.ctx().clone();
|
||||
const PER_FRAME: usize = 4;
|
||||
let mut budget = PER_FRAME;
|
||||
let mut more = false;
|
||||
for fam in lightningbeam_core::fonts::families() {
|
||||
if self.registered_preview_fonts.contains(&fam) {
|
||||
continue;
|
||||
}
|
||||
let bytes = lightningbeam_core::fonts::take_preloaded(&fam).or_else(|| {
|
||||
if dropdown_open { lightningbeam_core::fonts::family_font_bytes(&fam) } else { None }
|
||||
});
|
||||
if let Some(bytes) = bytes {
|
||||
if budget == 0 {
|
||||
more = true;
|
||||
break;
|
||||
}
|
||||
self.register_font_bytes(&ctx, &fam, bytes);
|
||||
budget -= 1;
|
||||
}
|
||||
}
|
||||
if more || !lightningbeam_core::fonts::preload_done() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Render clip instance info section
|
||||
fn render_clip_instance_section(&self, ui: &mut Ui, path: &NodePath, shared: &SharedPaneState, clip_ids: &[Uuid]) {
|
||||
let document = shared.action_executor.document();
|
||||
@@ -1203,6 +1584,7 @@ impl InfopanelPane {
|
||||
AnyLayer::Effect(l) => &l.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
if let Some(ci) = instances.iter().find(|c| c.id == ci_id) {
|
||||
found = true;
|
||||
@@ -1530,6 +1912,13 @@ impl PaneRenderer for InfopanelPane {
|
||||
}
|
||||
}
|
||||
|
||||
// Active raster layer's size + "to document size" — shown whenever a raster layer is
|
||||
// active (independent of selection focus, since painting doesn't focus the layer).
|
||||
if let Some(active_id) = *shared.active_layer_id {
|
||||
self.render_raster_layer_section(ui, path, shared, active_id);
|
||||
self.render_text_layer_section(ui, path, shared, active_id);
|
||||
}
|
||||
|
||||
// Onion-skinning view settings — always available, regardless of selection.
|
||||
ui.add_space(8.0);
|
||||
ui.separator();
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Shared horizontal keyboard geometry (pitch → x), used by both the Virtual Piano and the mobile
|
||||
//! portrait "Synthesia" Piano Roll so their columns line up with the keys. It is **width-driven**
|
||||
//! (key width from the pane width, not its height) and supports a smooth horizontal **pan** (pixels)
|
||||
//! so the roll and keyboard scroll together and stay aligned.
|
||||
|
||||
/// Number of white keys strictly before each pitch-class within its octave.
|
||||
const WHITES_BEFORE: [i32; 12] = [0, 1, 1, 2, 2, 3, 4, 4, 5, 5, 6, 6];
|
||||
/// White pitch-classes, indexed by white-key-within-octave.
|
||||
const WHITE_PC: [i32; 7] = [0, 2, 4, 5, 7, 9, 11];
|
||||
/// Target on-screen white-key width (px); the visible white-key count approximates it.
|
||||
const TARGET_WHITE_KEY_W: f32 = 40.0;
|
||||
|
||||
/// Absolute white-key index of a note, counting white keys from MIDI 0.
|
||||
fn awi(note: u8) -> i32 {
|
||||
(note as i32 / 12) * 7 + WHITES_BEFORE[(note % 12) as usize]
|
||||
}
|
||||
|
||||
/// The white note at a given absolute white-key index.
|
||||
fn white_note_from_awi(a: i32) -> u8 {
|
||||
let oct = a.div_euclid(7);
|
||||
let rem = a.rem_euclid(7) as usize;
|
||||
(oct * 12 + WHITE_PC[rem]).clamp(0, 127) as u8
|
||||
}
|
||||
|
||||
/// A horizontal piano key layout for a pane width, octave center, and horizontal pan.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct KeyboardLayout {
|
||||
pub white_key_width: f32,
|
||||
pub black_key_width: f32,
|
||||
/// `note_x(white n) == base_x + awi(n) * white_key_width`.
|
||||
base_x: f32,
|
||||
rect_left: f32,
|
||||
rect_width: f32,
|
||||
}
|
||||
|
||||
impl KeyboardLayout {
|
||||
pub fn is_black_key(note: u8) -> bool {
|
||||
matches!(note % 12, 1 | 3 | 6 | 8 | 10)
|
||||
}
|
||||
|
||||
/// Build a layout. `pan_x` shifts everything right (drag-right reveals lower keys); at `pan_x == 0`
|
||||
/// the octave-center key sits in the middle of the pane.
|
||||
pub fn from_width(origin_x: f32, width: f32, octave: i8, pan_x: f32) -> Self {
|
||||
let vis = ((width / TARGET_WHITE_KEY_W).round() as u32).clamp(7, 24) as f32;
|
||||
let white_key_width = width / vis;
|
||||
let black_key_width = white_key_width * 0.6;
|
||||
let center = (60 + octave as i32 * 12).clamp(0, 127) as u8;
|
||||
let base_x = origin_x + width / 2.0 - (awi(center) as f32 + 0.5) * white_key_width + pan_x;
|
||||
Self { white_key_width, black_key_width, base_x, rect_left: origin_x, rect_width: width }
|
||||
}
|
||||
|
||||
/// Snap a pan offset to the nearest whole key (for release-snap).
|
||||
pub fn snap_pan(&self, pan_x: f32) -> f32 {
|
||||
(pan_x / self.white_key_width).round() * self.white_key_width
|
||||
}
|
||||
|
||||
/// Left x of a key's rect (black keys straddle the white boundary).
|
||||
pub fn note_x(&self, note: u8) -> f32 {
|
||||
let x = self.base_x + awi(note) as f32 * self.white_key_width;
|
||||
if Self::is_black_key(note) {
|
||||
x - self.black_key_width / 2.0
|
||||
} else {
|
||||
x
|
||||
}
|
||||
}
|
||||
|
||||
pub fn note_width(&self, note: u8) -> f32 {
|
||||
if Self::is_black_key(note) {
|
||||
self.black_key_width
|
||||
} else {
|
||||
self.white_key_width
|
||||
}
|
||||
}
|
||||
|
||||
pub fn note_center_x(&self, note: u8) -> f32 {
|
||||
self.note_x(note) + self.note_width(note) / 2.0
|
||||
}
|
||||
|
||||
/// Leftmost visible white key (with one key of margin).
|
||||
pub fn first_visible_white(&self) -> u8 {
|
||||
let a = ((self.rect_left - self.base_x) / self.white_key_width).floor() as i32 - 1;
|
||||
white_note_from_awi(a.max(0))
|
||||
}
|
||||
|
||||
/// Rightmost visible note (with one key of margin).
|
||||
pub fn last_visible_note(&self) -> u8 {
|
||||
let a = ((self.rect_left + self.rect_width - self.base_x) / self.white_key_width).ceil() as i32 + 1;
|
||||
white_note_from_awi(a).min(127)
|
||||
}
|
||||
|
||||
pub fn visible_notes(&self) -> std::ops::RangeInclusive<u8> {
|
||||
self.first_visible_white()..=self.last_visible_note()
|
||||
}
|
||||
|
||||
/// Which key is at screen x (black keys, drawn on top, take precedence).
|
||||
pub fn x_to_note(&self, x: f32) -> u8 {
|
||||
for note in self.visible_notes() {
|
||||
if Self::is_black_key(note) {
|
||||
let c = self.note_center_x(note);
|
||||
if (x - c).abs() <= self.black_key_width / 2.0 {
|
||||
return note;
|
||||
}
|
||||
}
|
||||
}
|
||||
let a = ((x - self.base_x) / self.white_key_width).floor() as i32;
|
||||
white_note_from_awi(a.max(0)).min(127)
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,7 @@ pub mod gradient_editor;
|
||||
pub mod timeline;
|
||||
pub mod infopanel;
|
||||
pub mod outliner;
|
||||
pub mod keyboard_layout;
|
||||
pub mod piano_roll;
|
||||
pub mod virtual_piano;
|
||||
pub mod node_editor;
|
||||
@@ -212,10 +213,15 @@ pub struct SharedPaneState<'a> {
|
||||
pub editing_instance_id: Option<uuid::Uuid>,
|
||||
/// The parent layer ID containing the clip instance being edited
|
||||
pub editing_parent_layer_id: Option<uuid::Uuid>,
|
||||
/// The full clip_id path being edited, outermost → current (for breadcrumbs). Empty at root.
|
||||
pub editing_clip_path: Vec<uuid::Uuid>,
|
||||
/// Request to enter a movie clip for editing: (clip_id, instance_id, parent_layer_id)
|
||||
pub pending_enter_clip: &'a mut Option<(uuid::Uuid, uuid::Uuid, uuid::Uuid)>,
|
||||
/// Request to exit the current movie clip
|
||||
pub pending_exit_clip: &'a mut bool,
|
||||
/// Request to exit up to a specific editing depth (number of clips to keep); e.g. a breadcrumb
|
||||
/// click. `Some(0)` exits all the way to the document root.
|
||||
pub pending_exit_to_depth: &'a mut Option<usize>,
|
||||
/// Currently active layer ID
|
||||
pub active_layer_id: &'a mut Option<uuid::Uuid>,
|
||||
/// Current tool interaction state (mutable for tools to modify)
|
||||
@@ -356,6 +362,37 @@ pub struct SharedPaneState<'a> {
|
||||
/// on the first frame; panes (e.g. infopanel) convert the pixel data to egui
|
||||
/// TextureHandles. Each entry is `(width, height, sRGB-premultiplied RGBA bytes)`.
|
||||
pub brush_preview_pixels: &'a std::sync::Arc<std::sync::Mutex<Vec<(u32, u32, Vec<u8>)>>>,
|
||||
/// True when rendering the phone/mobile shell (panes can render more compactly).
|
||||
pub is_mobile: bool,
|
||||
/// Device orientation for the mobile shell: portrait (tall) vs landscape (wide). Defaults to
|
||||
/// `true`; the mobile shell sets it from the available rect. Panes that reflow (e.g. the Piano
|
||||
/// Roll's vertical vs conventional layout) key off this.
|
||||
pub is_portrait: bool,
|
||||
/// Shared keyboard octave offset (C4-relative), so the mobile Virtual Piano and the portrait
|
||||
/// Piano Roll agree on which keys are visible and stay column-aligned.
|
||||
pub keyboard_octave: &'a mut i8,
|
||||
/// Shared horizontal keyboard pan (px) for smooth left/right scroll of the mobile keyboard+roll.
|
||||
pub keyboard_pan_x: &'a mut f32,
|
||||
/// Whether the mobile instrument pane should show the falling-notes roll above the keys. Driven
|
||||
/// by the shell from the *snapped* pane size-class so the reveal happens at a stack snap point.
|
||||
pub instrument_show_roll: bool,
|
||||
/// Set by the mobile instrument header's "Presets" button; the shell opens the Preset Browser.
|
||||
pub open_instrument_browser: &'a mut bool,
|
||||
/// Set by the mobile instrument header's REC button; the Timeline pane picks it up and toggles
|
||||
/// recording (reusing its full count-in / clip-creation flow).
|
||||
pub pending_record_toggle: &'a mut bool,
|
||||
/// Mobile long-press context menu request. A pane sets this on `response.secondary_clicked()`
|
||||
/// (which fires on long-press) with the items relevant to what was pressed; the mobile shell
|
||||
/// renders one persistent popup and dispatches the chosen `MenuAction`. `None` = no menu.
|
||||
pub mobile_context_menu: &'a mut Option<MobileContextMenu>,
|
||||
}
|
||||
|
||||
/// A mobile long-press context menu: a screen position and a list of `(label, action)` items.
|
||||
/// Rendered by the mobile shell; each item dispatches its `MenuAction` via `pending_menu_actions`.
|
||||
#[derive(Clone)]
|
||||
pub struct MobileContextMenu {
|
||||
pub pos: egui::Pos2,
|
||||
pub items: Vec<(String, crate::menu::MenuAction)>,
|
||||
}
|
||||
|
||||
/// Trait for pane rendering
|
||||
|
||||
@@ -0,0 +1,741 @@
|
||||
//! Mobile (touch) node editor — Focus & Patch views (wireframe Plate 07).
|
||||
//!
|
||||
//! Swapped in for the desktop `draw_graph_editor` canvas when `shared.is_mobile`. Focus shows one
|
||||
//! module's parameters as big touch controls plus navigation; Patch does tap-to-cable wiring. All
|
||||
//! edits reuse the existing dispatch: mutating a param's `ValueType` in place is picked up by
|
||||
//! `check_parameter_changes`, and add/connect/disconnect go through `NodeGraphAction`.
|
||||
|
||||
use super::graph_data::{DataType, NodeTemplate, ValueType};
|
||||
use super::{actions, NodeGraphPane};
|
||||
use crate::mobile::icons;
|
||||
use eframe::egui;
|
||||
use egui_node_graph2::{InputId, InputParamKind, NodeDataTrait, NodeId, NodeTemplateTrait, OutputId};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NodeViewMode {
|
||||
Focus,
|
||||
Patch,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PortDir {
|
||||
In,
|
||||
Out,
|
||||
}
|
||||
|
||||
/// An armed port awaiting a compatible endpoint to cable to.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PatchPick {
|
||||
node: NodeId,
|
||||
port: usize,
|
||||
dir: PortDir,
|
||||
typ: DataType,
|
||||
}
|
||||
|
||||
pub struct MobileNodeState {
|
||||
pub mode: NodeViewMode,
|
||||
/// The module currently shown in Focus (and centred in Patch).
|
||||
pub focus_node: Option<NodeId>,
|
||||
/// Armed cable source in Patch: (node, output-port index).
|
||||
pub patch_source: Option<(NodeId, usize)>,
|
||||
/// Whether the add-node picker overlay is open.
|
||||
pub show_add: bool,
|
||||
/// Search filter in the add-node picker.
|
||||
pub add_search: String,
|
||||
/// Armed port in Patch awaiting a compatible endpoint.
|
||||
patch_pick: Option<PatchPick>,
|
||||
}
|
||||
|
||||
impl Default for MobileNodeState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: NodeViewMode::Focus,
|
||||
focus_node: None,
|
||||
patch_source: None,
|
||||
show_add: false,
|
||||
add_search: String::new(),
|
||||
patch_pick: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeGraphPane {
|
||||
pub(super) fn render_mobile(
|
||||
&mut self,
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
shared: &mut crate::panes::SharedPaneState,
|
||||
) {
|
||||
let bg = shared.theme.bg_color(&["#node-editor", ".pane-content"], ui.ctx(), egui::Color32::from_gray(28));
|
||||
ui.painter().rect_filled(rect, 0.0, bg);
|
||||
|
||||
// Resolve the focus node: keep the current one if it still exists, else the selected node,
|
||||
// else the first node in the graph.
|
||||
let focus_valid = self
|
||||
.mobile
|
||||
.focus_node
|
||||
.map_or(false, |id| self.state.graph.nodes.get(id).is_some());
|
||||
if !focus_valid {
|
||||
self.mobile.focus_node = self
|
||||
.state
|
||||
.selected_nodes
|
||||
.iter()
|
||||
.next()
|
||||
.copied()
|
||||
.or_else(|| self.state.graph.iter_nodes().next());
|
||||
}
|
||||
|
||||
// Header: Focus/Patch toggle + focused node name.
|
||||
let header_h = 44.0;
|
||||
let header = egui::Rect::from_min_max(rect.min, egui::pos2(rect.right(), rect.top() + header_h));
|
||||
let body = egui::Rect::from_min_max(egui::pos2(rect.left(), header.bottom()), rect.max);
|
||||
|
||||
let name = self
|
||||
.mobile
|
||||
.focus_node
|
||||
.and_then(|id| self.state.graph.nodes.get(id))
|
||||
.map(|n| n.label.clone())
|
||||
.unwrap_or_else(|| "—".to_string());
|
||||
ui.painter().line_segment(
|
||||
[egui::pos2(header.left(), header.bottom()), egui::pos2(header.right(), header.bottom())],
|
||||
egui::Stroke::new(1.0, egui::Color32::from_gray(60)),
|
||||
);
|
||||
let mut mode = self.mobile.mode;
|
||||
ui.scope_builder(
|
||||
egui::UiBuilder::new().max_rect(header.shrink(8.0)).layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
|ui| {
|
||||
if ui.selectable_label(mode == NodeViewMode::Focus, "Focus").clicked() {
|
||||
mode = NodeViewMode::Focus;
|
||||
}
|
||||
if ui.selectable_label(mode == NodeViewMode::Patch, "Patch").clicked() {
|
||||
mode = NodeViewMode::Patch;
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
ui.label(egui::RichText::new(name).strong());
|
||||
},
|
||||
);
|
||||
self.mobile.mode = mode;
|
||||
|
||||
// Keep backend-id map current so embedded `bottom_ui` (sampler/script/etc.) targets the
|
||||
// right backend node (mirrors the desktop pre-draw sync).
|
||||
self.user_state.node_backend_ids = self
|
||||
.node_id_map
|
||||
.iter()
|
||||
.map(|(&nid, bid)| (nid, bid.index()))
|
||||
.collect();
|
||||
|
||||
match self.mobile.mode {
|
||||
NodeViewMode::Focus => self.render_mobile_focus(ui, body, shared),
|
||||
NodeViewMode::Patch => self.render_mobile_patch(ui, body, shared),
|
||||
}
|
||||
|
||||
// Same dispatch tail as the desktop path: apply param edits and run any queued action.
|
||||
self.check_parameter_changes(shared);
|
||||
self.execute_pending_action(shared);
|
||||
|
||||
// Drain the custom-UI loads that have self-contained handlers (sampler + script sample).
|
||||
// Other bespoke interactions (sequencer grid, NAM model, script canvas) are a case-by-case
|
||||
// follow-up; clear their queues so they don't accumulate.
|
||||
if let Some(load) = self.user_state.pending_sampler_load.take() {
|
||||
self.handle_pending_sampler_load(load, shared);
|
||||
}
|
||||
if let Some(load) = self.user_state.pending_script_sample_load.take() {
|
||||
self.handle_pending_script_sample_load(load, shared);
|
||||
}
|
||||
self.user_state.pending_sequencer_changes.clear();
|
||||
self.user_state.pending_draw_param_changes.clear();
|
||||
self.user_state.pending_root_note_changes.clear();
|
||||
}
|
||||
|
||||
fn render_mobile_focus(
|
||||
&mut self,
|
||||
ui: &mut egui::Ui,
|
||||
body: egui::Rect,
|
||||
shared: &mut crate::panes::SharedPaneState,
|
||||
) {
|
||||
let Some(focus) = self.mobile.focus_node else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Full-width minimap strip across the top; everything else below it.
|
||||
let mm_h = 96.0;
|
||||
let mm = egui::Rect::from_min_max(body.min, egui::pos2(body.right(), body.top() + mm_h));
|
||||
// Reserve an add-node button strip at the bottom.
|
||||
let add_h = 46.0;
|
||||
let add_rect = egui::Rect::from_min_max(egui::pos2(body.left(), body.bottom() - add_h), body.max);
|
||||
let content = egui::Rect::from_min_max(egui::pos2(body.left(), mm.bottom()), egui::pos2(body.right(), add_rect.top()));
|
||||
|
||||
// Minimap first (tap a node to focus it).
|
||||
let mut jump: Option<NodeId> = self.render_minimap(ui, mm, focus);
|
||||
|
||||
// Connection travel chips (owned) + params.
|
||||
let (in_chips, out_chips) = self.focus_chips(focus);
|
||||
let inputs: Vec<(String, InputId)> = self
|
||||
.state
|
||||
.graph
|
||||
.nodes
|
||||
.get(focus)
|
||||
.map(|n| n.inputs.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
ui.scope_builder(
|
||||
egui::UiBuilder::new().max_rect(content.shrink(10.0)).layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
|ui| {
|
||||
if !in_chips.is_empty() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(egui::RichText::new("in").weak());
|
||||
for (label, node) in &in_chips {
|
||||
if ui.button(label.as_str()).clicked() {
|
||||
jump = Some(*node);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if !out_chips.is_empty() {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.label(egui::RichText::new("out").weak());
|
||||
for (label, node) in &out_chips {
|
||||
if ui.button(label.as_str()).clicked() {
|
||||
jump = Some(*node);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if !in_chips.is_empty() || !out_chips.is_empty() {
|
||||
ui.separator();
|
||||
}
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
let mut any = false;
|
||||
for (name, input_id) in &inputs {
|
||||
let Some(param) = self.state.graph.inputs.get_mut(*input_id) else {
|
||||
continue;
|
||||
};
|
||||
if matches!(param.kind, InputParamKind::ConnectionOnly) {
|
||||
continue;
|
||||
}
|
||||
any = true;
|
||||
render_param_row(ui, name, &mut param.value);
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
if !any {
|
||||
ui.label(egui::RichText::new("No editable parameters").weak());
|
||||
}
|
||||
// Embedded desktop custom UI (sampler picker, sequencer grid, script UI, …).
|
||||
// Standard nodes render nothing here.
|
||||
if let Some(node) = self.state.graph.nodes.get(focus) {
|
||||
let _ = node.user_data.bottom_ui(ui, focus, &self.state.graph, &mut self.user_state);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Add-node button.
|
||||
ui.scope_builder(
|
||||
egui::UiBuilder::new().max_rect(add_rect.shrink(8.0)).layout(egui::Layout::left_to_right(egui::Align::Center)),
|
||||
|ui| {
|
||||
if ui.button(egui::RichText::new("+ Add node").size(15.0)).clicked() {
|
||||
self.mobile.show_add = true;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if let Some(nid) = jump {
|
||||
self.mobile.focus_node = Some(nid);
|
||||
}
|
||||
|
||||
if self.mobile.show_add {
|
||||
self.render_add_picker(ui, body, shared);
|
||||
}
|
||||
}
|
||||
|
||||
/// Connection chips for the focus node: (label, remote node) for upstream inputs and downstream
|
||||
/// outputs. Label names the remote endpoint (`node ▸ port`).
|
||||
fn focus_chips(&self, focus: NodeId) -> (Vec<(String, NodeId)>, Vec<(String, NodeId)>) {
|
||||
let mut ins = Vec::new();
|
||||
let mut outs = Vec::new();
|
||||
for (input_id, outputs) in self.state.graph.iter_connection_groups() {
|
||||
let in_node = self.state.graph.inputs.get(input_id).map(|p| p.node);
|
||||
for output_id in outputs {
|
||||
let out_node = self.state.graph.outputs.get(output_id).map(|p| p.node);
|
||||
if in_node == Some(focus) {
|
||||
if let Some(src) = out_node {
|
||||
ins.push((format!("{} · {}", self.node_label(src), self.output_port_name(src, output_id)), src));
|
||||
}
|
||||
}
|
||||
if out_node == Some(focus) {
|
||||
if let Some(dst) = in_node {
|
||||
outs.push((format!("{} · {}", self.node_label(dst), self.input_port_name(dst, input_id)), dst));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(ins, outs)
|
||||
}
|
||||
|
||||
fn node_label(&self, n: NodeId) -> String {
|
||||
self.state.graph.nodes.get(n).map(|x| x.label.clone()).unwrap_or_default()
|
||||
}
|
||||
fn output_port_name(&self, n: NodeId, oid: OutputId) -> String {
|
||||
self.state
|
||||
.graph
|
||||
.nodes
|
||||
.get(n)
|
||||
.and_then(|node| node.outputs.iter().find(|(_, id)| *id == oid).map(|(nm, _)| nm.clone()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
fn input_port_name(&self, n: NodeId, iid: InputId) -> String {
|
||||
self.state
|
||||
.graph
|
||||
.nodes
|
||||
.get(n)
|
||||
.and_then(|node| node.inputs.iter().find(|(_, id)| *id == iid).map(|(nm, _)| nm.clone()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Draw a minimap of the graph; returns a node id if the user tapped one.
|
||||
fn render_minimap(&self, ui: &mut egui::Ui, rect: egui::Rect, focus: NodeId) -> Option<NodeId> {
|
||||
let painter = ui.painter_at(rect);
|
||||
painter.rect_filled(rect, 4.0, egui::Color32::from_rgba_unmultiplied(0, 0, 0, 120));
|
||||
painter.rect_stroke(rect, 4.0, egui::Stroke::new(1.0, egui::Color32::from_gray(70)), egui::StrokeKind::Inside);
|
||||
|
||||
let nodes: Vec<(NodeId, egui::Pos2)> = self
|
||||
.state
|
||||
.graph
|
||||
.iter_nodes()
|
||||
.filter_map(|n| self.state.node_positions.get(n).map(|p| (n, *p)))
|
||||
.collect();
|
||||
if nodes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (mut mnx, mut mny, mut mxx, mut mxy) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
|
||||
for (_, p) in &nodes {
|
||||
mnx = mnx.min(p.x);
|
||||
mny = mny.min(p.y);
|
||||
mxx = mxx.max(p.x);
|
||||
mxy = mxy.max(p.y);
|
||||
}
|
||||
let pad = 10.0;
|
||||
let inner = rect.shrink(pad);
|
||||
let span = egui::vec2((mxx - mnx).max(1.0), (mxy - mny).max(1.0));
|
||||
let map = |p: egui::Pos2| {
|
||||
egui::pos2(
|
||||
inner.left() + (p.x - mnx) / span.x * inner.width(),
|
||||
inner.top() + (p.y - mny) / span.y * inner.height(),
|
||||
)
|
||||
};
|
||||
|
||||
// Connection lines.
|
||||
for (input_id, outputs) in self.state.graph.iter_connection_groups() {
|
||||
let in_pos = self.state.graph.inputs.get(input_id).and_then(|p| self.state.node_positions.get(p.node)).copied();
|
||||
for output_id in outputs {
|
||||
let out_pos = self.state.graph.outputs.get(output_id).and_then(|p| self.state.node_positions.get(p.node)).copied();
|
||||
if let (Some(a), Some(b)) = (out_pos, in_pos) {
|
||||
painter.line_segment([map(a), map(b)], egui::Stroke::new(1.0, egui::Color32::from_gray(90)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let resp = ui.interact(rect, ui.id().with("node_minimap"), egui::Sense::click());
|
||||
let click = if resp.clicked() { resp.interact_pointer_pos() } else { None };
|
||||
let mut hit = None;
|
||||
let mut best_d = f32::MAX;
|
||||
for (nid, p) in &nodes {
|
||||
let c = map(*p);
|
||||
let focused = *nid == focus;
|
||||
let color = if focused { egui::Color32::from_rgb(0x4a, 0xa3, 0xff) } else { egui::Color32::from_gray(200) };
|
||||
painter.circle_filled(c, if focused { 7.0 } else { 5.0 }, color);
|
||||
if focused {
|
||||
painter.circle_stroke(c, 9.0, egui::Stroke::new(1.5, color));
|
||||
}
|
||||
// Tap selects the nearest node (dots are small, so don't require a precise hit).
|
||||
if let Some(cp) = click {
|
||||
let d = (cp - c).length();
|
||||
if d < best_d {
|
||||
best_d = d;
|
||||
hit = Some(*nid);
|
||||
}
|
||||
}
|
||||
}
|
||||
hit
|
||||
}
|
||||
|
||||
/// The add-node picker overlay: a searchable list of templates.
|
||||
fn render_add_picker(&mut self, ui: &mut egui::Ui, body: egui::Rect, shared: &mut crate::panes::SharedPaneState) {
|
||||
let panel = egui::Rect::from_center_size(body.center(), egui::vec2(body.width().min(320.0), body.height().min(420.0)));
|
||||
let mut chosen: Option<NodeTemplate> = None;
|
||||
let mut close = false;
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(panel), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new("Add node").strong());
|
||||
if ui.button("✕").clicked() {
|
||||
close = true;
|
||||
}
|
||||
});
|
||||
ui.add(egui::TextEdit::singleline(&mut self.mobile.add_search).hint_text("Search…"));
|
||||
let q = self.mobile.add_search.to_lowercase();
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
for template in NodeTemplate::all_finder_kinds() {
|
||||
let label = template.node_finder_label(&mut self.user_state).to_string();
|
||||
if !q.is_empty() && !label.to_lowercase().contains(&q) {
|
||||
continue;
|
||||
}
|
||||
if ui.button(&label).clicked() {
|
||||
chosen = Some(template);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if let Some(t) = chosen {
|
||||
self.mobile_add_node(t, shared);
|
||||
self.mobile.show_add = false;
|
||||
self.mobile.add_search.clear();
|
||||
}
|
||||
if close {
|
||||
self.mobile.show_add = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a node (frontend + backend action) and focus it, mirroring the desktop CreatedNode path.
|
||||
fn mobile_add_node(&mut self, template: NodeTemplate, _shared: &mut crate::panes::SharedPaneState) {
|
||||
let Some(track_id) = self.track_id else {
|
||||
return;
|
||||
};
|
||||
// Place near the current focus node, else the origin.
|
||||
let base = self
|
||||
.mobile
|
||||
.focus_node
|
||||
.and_then(|id| self.state.node_positions.get(id).copied())
|
||||
.unwrap_or(egui::Pos2::ZERO);
|
||||
let pos = base + egui::vec2(160.0, 0.0);
|
||||
|
||||
let label = template.node_graph_label(&mut self.user_state);
|
||||
let user_data = template.user_data(&mut self.user_state);
|
||||
let new_id = self
|
||||
.state
|
||||
.graph
|
||||
.add_node(label, user_data, |graph, id| template.build_node(graph, &mut self.user_state, id));
|
||||
self.state.node_positions.insert(new_id, pos);
|
||||
|
||||
let node_type = template.backend_type_name().to_string();
|
||||
self.pending_action = Some(Box::new(actions::NodeGraphAction::AddNode(
|
||||
actions::AddNodeAction::new(track_id, node_type.clone(), (pos.x, pos.y)),
|
||||
)));
|
||||
self.pending_node_addition = Some((new_id, node_type, (pos.x, pos.y)));
|
||||
self.mobile.focus_node = Some(new_id);
|
||||
}
|
||||
|
||||
fn render_mobile_patch(
|
||||
&mut self,
|
||||
ui: &mut egui::Ui,
|
||||
body: egui::Rect,
|
||||
_shared: &mut crate::panes::SharedPaneState,
|
||||
) {
|
||||
let Some(focus) = self.mobile.focus_node else {
|
||||
return;
|
||||
};
|
||||
|
||||
// Build owned row data (immutable reads) so rendering can freely queue ops.
|
||||
let inputs: Vec<(String, InputId)> = self.state.graph.nodes.get(focus).map(|n| n.inputs.clone()).unwrap_or_default();
|
||||
let outputs: Vec<(String, OutputId)> = self.state.graph.nodes.get(focus).map(|n| n.outputs.clone()).unwrap_or_default();
|
||||
|
||||
// Rows: (idx, name, type, cables[(remote_node, remote_port, other_node, other_port)]).
|
||||
let mut in_rows: Vec<(usize, String, DataType, Vec<(String, String, NodeId, usize)>)> = Vec::new();
|
||||
for (idx, (name, input_id)) in inputs.iter().enumerate() {
|
||||
let Some(typ) = self.state.graph.inputs.get(*input_id).map(|p| p.typ) else { continue };
|
||||
let mut cables = Vec::new();
|
||||
if let Some(outs) = self.state.graph.connections.get(*input_id) {
|
||||
for oid in outs {
|
||||
if let Some(src) = self.state.graph.outputs.get(*oid).map(|o| o.node) {
|
||||
let sp = self.output_port_index(src, *oid);
|
||||
cables.push((self.node_label(src), self.output_port_name(src, *oid), src, sp));
|
||||
}
|
||||
}
|
||||
}
|
||||
in_rows.push((idx, name.clone(), typ, cables));
|
||||
}
|
||||
let mut out_rows: Vec<(usize, String, DataType, Vec<(String, String, NodeId, usize)>)> = Vec::new();
|
||||
for (idx, (name, output_id)) in outputs.iter().enumerate() {
|
||||
let Some(typ) = self.state.graph.outputs.get(*output_id).map(|o| o.typ) else { continue };
|
||||
let mut cables = Vec::new();
|
||||
for (input_id, outs) in self.state.graph.iter_connection_groups() {
|
||||
if outs.iter().any(|o| o == output_id) {
|
||||
if let Some(dst) = self.state.graph.inputs.get(input_id).map(|i| i.node) {
|
||||
let dp = self.input_port_index(dst, input_id);
|
||||
cables.push((self.node_label(dst), self.input_port_name(dst, input_id), dst, dp));
|
||||
}
|
||||
}
|
||||
}
|
||||
out_rows.push((idx, name.clone(), typ, cables));
|
||||
}
|
||||
|
||||
// Queue ops during render, apply after (avoids borrowing self mid-render).
|
||||
enum Op {
|
||||
Disconnect(NodeId, usize, NodeId, usize), // (out_node, out_port, in_node, in_port)
|
||||
Connect(NodeId, usize, NodeId, usize),
|
||||
Pick(PatchPick),
|
||||
ClearPick,
|
||||
}
|
||||
let mut ops: Vec<Op> = Vec::new();
|
||||
let pick = self.mobile.patch_pick;
|
||||
|
||||
ui.scope_builder(
|
||||
egui::UiBuilder::new().max_rect(body.shrink(10.0)).layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
|ui| {
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
// A Grid aligns each section's port arrows into a column. Tapping a port arrow
|
||||
// arms a cable from it (also for unconnected ports); tapping a cable chip removes
|
||||
// it. Inputs read `[cables] ⥓ name`; outputs read `name ↦ [cables]`.
|
||||
ui.label(egui::RichText::new("Inputs").weak());
|
||||
egui::Grid::new("patch_inputs").num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
for (idx, name, typ, cables) in &in_rows {
|
||||
ui.horizontal(|ui| {
|
||||
for (rnode, rport, sn, sp) in cables {
|
||||
if cable_chip(ui, rnode, rport, *typ).clicked() {
|
||||
ops.push(Op::Disconnect(*sn, *sp, focus, *idx));
|
||||
}
|
||||
}
|
||||
});
|
||||
if arrow_button(ui, icons::ARROW_RIGHT_TO_LINE, *typ).clicked() {
|
||||
ops.push(Op::Pick(PatchPick { node: focus, port: *idx, dir: PortDir::In, typ: *typ }));
|
||||
}
|
||||
ui.label(name.as_str());
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
ui.label(egui::RichText::new("Outputs").weak());
|
||||
egui::Grid::new("patch_outputs").num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| {
|
||||
for (idx, name, typ, cables) in &out_rows {
|
||||
ui.label(name.as_str());
|
||||
if arrow_button(ui, icons::ARROW_RIGHT_FROM_LINE, *typ).clicked() {
|
||||
ops.push(Op::Pick(PatchPick { node: focus, port: *idx, dir: PortDir::Out, typ: *typ }));
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
for (rnode, rport, dn, dp) in cables {
|
||||
if cable_chip(ui, rnode, rport, *typ).clicked() {
|
||||
ops.push(Op::Disconnect(focus, *idx, *dn, *dp));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Compatible-endpoint picker overlay when a port is armed.
|
||||
if let Some(p) = pick {
|
||||
let candidates = self.patch_candidates(p);
|
||||
let panel = egui::Rect::from_center_size(body.center(), egui::vec2(body.width().min(320.0), body.height().min(360.0)));
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(panel), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
port_marker(ui, p.typ, p.dir);
|
||||
ui.label(egui::RichText::new("Connect to…").strong());
|
||||
if ui.button("✕").clicked() {
|
||||
ops.push(Op::ClearPick);
|
||||
}
|
||||
});
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
if candidates.is_empty() {
|
||||
ui.label(egui::RichText::new("No compatible ports").weak());
|
||||
}
|
||||
for (label, other, other_port) in &candidates {
|
||||
if ui.button(egui::RichText::new(label.as_str()).color(type_color(p.typ))).clicked() {
|
||||
// Orient the cable: armed In needs an Out source; armed Out needs an In target.
|
||||
match p.dir {
|
||||
PortDir::In => ops.push(Op::Connect(*other, *other_port, p.node, p.port)),
|
||||
PortDir::Out => ops.push(Op::Connect(p.node, p.port, *other, *other_port)),
|
||||
}
|
||||
ops.push(Op::ClearPick);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
for op in ops {
|
||||
match op {
|
||||
Op::Disconnect(on, op_, inn, ip) => self.mobile_disconnect(on, op_, inn, ip),
|
||||
Op::Connect(on, op_, inn, ip) => self.mobile_connect(on, op_, inn, ip),
|
||||
Op::Pick(p) => self.mobile.patch_pick = Some(p),
|
||||
Op::ClearPick => self.mobile.patch_pick = None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compatible endpoints on OTHER nodes for an armed port (opposite direction, same type).
|
||||
fn patch_candidates(&self, p: PatchPick) -> Vec<(String, NodeId, usize)> {
|
||||
let mut out = Vec::new();
|
||||
for node in self.state.graph.iter_nodes() {
|
||||
if node == p.node {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = self.state.graph.nodes.get(node) else { continue };
|
||||
match p.dir {
|
||||
// Armed input → list outputs of matching type.
|
||||
PortDir::In => {
|
||||
for (i, (name, oid)) in n.outputs.iter().enumerate() {
|
||||
if self.state.graph.outputs.get(*oid).map(|o| o.typ) == Some(p.typ) {
|
||||
out.push((format!("{} · {}", self.node_label(node), name), node, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Armed output → list inputs of matching type.
|
||||
PortDir::Out => {
|
||||
for (i, (name, iid)) in n.inputs.iter().enumerate() {
|
||||
if self.state.graph.inputs.get(*iid).map(|x| x.typ) == Some(p.typ) {
|
||||
out.push((format!("{} · {}", self.node_label(node), name), node, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn output_port_index(&self, n: NodeId, oid: OutputId) -> usize {
|
||||
self.state.graph.nodes.get(n).and_then(|node| node.outputs.iter().position(|(_, id)| *id == oid)).unwrap_or(0)
|
||||
}
|
||||
fn input_port_index(&self, n: NodeId, iid: InputId) -> usize {
|
||||
self.state.graph.nodes.get(n).and_then(|node| node.inputs.iter().position(|(_, id)| *id == iid)).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Cable an output port → input port: update the frontend graph + dispatch `Connect`.
|
||||
fn mobile_connect(&mut self, out_node: NodeId, out_port: usize, in_node: NodeId, in_port: usize) {
|
||||
// Mobile has no subgraph navigation yet, so cables always target the track-level graph. If
|
||||
// subgraph nav is added, route through `va_context()` / `graph_connect_in_template` like desktop.
|
||||
debug_assert!(self.subgraph_stack.is_empty(), "mobile node connect assumes the top-level graph");
|
||||
let Some(track_id) = self.track_id else { return };
|
||||
let output_id = self.state.graph.nodes.get(out_node).and_then(|n| n.outputs.get(out_port)).map(|(_, id)| *id);
|
||||
let input_id = self.state.graph.nodes.get(in_node).and_then(|n| n.inputs.get(in_port)).map(|(_, id)| *id);
|
||||
let (Some(output_id), Some(input_id)) = (output_id, input_id) else { return };
|
||||
if let Some(conns) = self.state.graph.connections.get_mut(input_id) {
|
||||
if !conns.contains(&output_id) {
|
||||
conns.push(output_id);
|
||||
}
|
||||
} else {
|
||||
self.state.graph.connections.insert(input_id, vec![output_id]);
|
||||
}
|
||||
if let (Some(&from_id), Some(&to_id)) = (self.node_id_map.get(&out_node), self.node_id_map.get(&in_node)) {
|
||||
self.pending_action = Some(Box::new(actions::NodeGraphAction::Connect(
|
||||
actions::ConnectAction::new(track_id, from_id, out_port, to_id, in_port),
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a cable: update the frontend graph + dispatch `Disconnect`. Like `mobile_connect`, this
|
||||
/// assumes the track-level graph (mobile has no subgraph navigation).
|
||||
fn mobile_disconnect(&mut self, out_node: NodeId, out_port: usize, in_node: NodeId, in_port: usize) {
|
||||
debug_assert!(self.subgraph_stack.is_empty(), "mobile node disconnect assumes the top-level graph");
|
||||
let Some(track_id) = self.track_id else { return };
|
||||
let output_id = self.state.graph.nodes.get(out_node).and_then(|n| n.outputs.get(out_port)).map(|(_, id)| *id);
|
||||
let input_id = self.state.graph.nodes.get(in_node).and_then(|n| n.inputs.get(in_port)).map(|(_, id)| *id);
|
||||
let (Some(output_id), Some(input_id)) = (output_id, input_id) else { return };
|
||||
if let Some(conns) = self.state.graph.connections.get_mut(input_id) {
|
||||
conns.retain(|o| *o != output_id);
|
||||
}
|
||||
if let (Some(&from_id), Some(&to_id)) = (self.node_id_map.get(&out_node), self.node_id_map.get(&in_node)) {
|
||||
self.pending_action = Some(Box::new(actions::NodeGraphAction::Disconnect(
|
||||
actions::DisconnectAction::new(track_id, from_id, out_port, to_id, in_port),
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Desktop port color per signal type (matches `DataType::data_type_color`).
|
||||
fn type_color(t: DataType) -> egui::Color32 {
|
||||
match t {
|
||||
DataType::Audio => egui::Color32::from_rgb(100, 150, 255), // blue
|
||||
DataType::Midi => egui::Color32::from_rgb(100, 255, 100), // green
|
||||
DataType::CV => egui::Color32::from_rgb(255, 150, 100), // orange
|
||||
}
|
||||
}
|
||||
|
||||
/// A single Lucide direction arrow glyph, tinted by signal type.
|
||||
fn arrow(ui: &mut egui::Ui, glyph: &str, t: DataType) {
|
||||
ui.label(
|
||||
egui::RichText::new(glyph)
|
||||
.color(type_color(t))
|
||||
.family(egui::FontFamily::Name(icons::FAMILY.into()))
|
||||
.size(15.0),
|
||||
);
|
||||
}
|
||||
|
||||
/// A port marker: a Lucide direction arrow (out = from-line, in = to-line) tinted by signal type.
|
||||
fn port_marker(ui: &mut egui::Ui, t: DataType, dir: PortDir) {
|
||||
let glyph = match dir {
|
||||
PortDir::In => icons::ARROW_RIGHT_TO_LINE,
|
||||
PortDir::Out => icons::ARROW_RIGHT_FROM_LINE,
|
||||
};
|
||||
arrow(ui, glyph, t);
|
||||
}
|
||||
|
||||
/// A clickable, aligned port arrow (out = from-line, in = to-line) tinted by signal type. Tapping it
|
||||
/// arms a cable from the port. Frameless so it reads like the desktop port dot.
|
||||
fn arrow_button(ui: &mut egui::Ui, glyph: &str, t: DataType) -> egui::Response {
|
||||
ui.add(
|
||||
egui::Button::new(
|
||||
egui::RichText::new(glyph)
|
||||
.color(type_color(t))
|
||||
.family(egui::FontFamily::Name(icons::FAMILY.into()))
|
||||
.size(16.0),
|
||||
)
|
||||
.frame(false),
|
||||
)
|
||||
}
|
||||
|
||||
/// A cable badge naming the remote endpoint (`remote-node · remote-port`), framed and tinted by
|
||||
/// signal type. Returns a click response (used to disconnect the cable).
|
||||
fn cable_chip(ui: &mut egui::Ui, remote_node: &str, remote_port: &str, t: DataType) -> egui::Response {
|
||||
egui::Frame::group(ui.style())
|
||||
.inner_margin(egui::Margin::symmetric(6, 1))
|
||||
.show(ui, |ui| {
|
||||
ui.label(egui::RichText::new(format!("{remote_node} · {remote_port}")).color(type_color(t)));
|
||||
})
|
||||
.response
|
||||
.interact(egui::Sense::click())
|
||||
}
|
||||
|
||||
/// One parameter row: a touch control matching the desktop widget rule (enum → dropdown, ranged →
|
||||
/// slider, plain → stepper, string → field). Mutates the value in place; dispatch happens later via
|
||||
/// `check_parameter_changes`.
|
||||
fn render_param_row(ui: &mut egui::Ui, name: &str, value: &mut ValueType) {
|
||||
match value {
|
||||
ValueType::Float { value, min, max, unit, enum_labels, .. } => {
|
||||
ui.label(name);
|
||||
if let Some(labels) = enum_labels {
|
||||
let mut sel = (*value as usize).min(labels.len().saturating_sub(1));
|
||||
egui::ComboBox::from_id_salt(name)
|
||||
.width(ui.available_width().min(240.0))
|
||||
.selected_text(labels.get(sel).copied().unwrap_or("?"))
|
||||
.show_ui(ui, |ui| {
|
||||
for (i, label) in labels.iter().enumerate() {
|
||||
ui.selectable_value(&mut sel, i, *label);
|
||||
}
|
||||
});
|
||||
*value = sel as f32;
|
||||
} else if *max > *min {
|
||||
// Give the rail a visible color so the full track length reads (the theme's default
|
||||
// inactive fill can be near-transparent); trailing_fill shows progress along it.
|
||||
ui.scope(|ui| {
|
||||
let rail = egui::Color32::from_gray(90);
|
||||
ui.visuals_mut().widgets.inactive.bg_fill = rail;
|
||||
ui.visuals_mut().widgets.inactive.weak_bg_fill = rail;
|
||||
ui.visuals_mut().widgets.hovered.bg_fill = rail;
|
||||
ui.add(egui::Slider::new(value, *min..=*max).suffix(*unit).trailing_fill(true));
|
||||
});
|
||||
} else {
|
||||
ui.add(egui::DragValue::new(value).speed(0.1));
|
||||
}
|
||||
}
|
||||
ValueType::String { value } => {
|
||||
ui.label(name);
|
||||
ui.text_edit_singleline(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ pub mod actions;
|
||||
pub mod audio_backend;
|
||||
pub mod backend;
|
||||
pub mod graph_data;
|
||||
mod mobile;
|
||||
|
||||
use backend::{BackendNodeId, GraphBackend};
|
||||
use graph_data::{AllNodeTemplates, SubgraphNodeTemplates, VoiceAllocatorNodeTemplates, DataType, GraphState, NamModelInfo, NodeData, NodeTemplate, PendingAmpSimLoad, ValueType};
|
||||
@@ -142,6 +143,9 @@ pub struct NodeGraphPane {
|
||||
last_oscilloscope_poll: std::time::Instant,
|
||||
/// Backend track ID (u32) for oscilloscope queries
|
||||
backend_track_id: Option<u32>,
|
||||
|
||||
/// Mobile (touch) Focus/Patch view state.
|
||||
mobile: mobile::MobileNodeState,
|
||||
}
|
||||
|
||||
impl NodeGraphPane {
|
||||
@@ -171,6 +175,7 @@ impl NodeGraphPane {
|
||||
pending_script_resolutions: Vec::new(),
|
||||
last_oscilloscope_poll: std::time::Instant::now(),
|
||||
backend_track_id: None,
|
||||
mobile: mobile::MobileNodeState::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2365,6 +2370,13 @@ impl crate::panes::PaneRenderer for NodeGraphPane {
|
||||
painter.galley(text_pos, galley, text_color);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mobile: touch-native Focus/Patch views instead of the desktop canvas.
|
||||
if shared.is_mobile {
|
||||
self.render_mobile(ui, rect, shared);
|
||||
return;
|
||||
}
|
||||
|
||||
// Poll oscilloscope data at ~20 FPS
|
||||
let has_oscilloscopes;
|
||||
if self.last_oscilloscope_poll.elapsed() >= std::time::Duration::from_millis(50) {
|
||||
|
||||
@@ -169,6 +169,20 @@ pub struct PianoRollPane {
|
||||
snap_value: SnapValue,
|
||||
last_snap_selection: HashSet<usize>,
|
||||
snap_user_changed: bool, // set in render_header, consumed before handle_input
|
||||
|
||||
// Mobile portrait "Synthesia" mode: the playable keyboard is drawn as a strip at the bottom of
|
||||
// this pane (one unified surface), reusing the Virtual Piano's rendering + MIDI logic.
|
||||
keyboard: super::virtual_piano::VirtualPianoPane,
|
||||
// Landscape mobile: the Keys/Notes toggle — true shows the full keyboard, false the roll.
|
||||
landscape_keys: bool,
|
||||
// Manual long-press detection for the vertical roll (works with mouse-hold and touch): time the
|
||||
// press started, and where. `None` = disarmed (no fresh press, or the press became a pan).
|
||||
lp_press_time: Option<f64>,
|
||||
lp_press_pos: egui::Pos2,
|
||||
// When the long-press landed on an existing note, we resize it instead of creating: its index in
|
||||
// the resolved-note list and its original duration (to compute the resize delta on commit).
|
||||
editing_index: Option<usize>,
|
||||
editing_orig_dur: f64,
|
||||
}
|
||||
|
||||
impl PianoRollPane {
|
||||
@@ -205,6 +219,12 @@ impl PianoRollPane {
|
||||
snap_value: SnapValue::None,
|
||||
last_snap_selection: HashSet::new(),
|
||||
snap_user_changed: false,
|
||||
keyboard: super::virtual_piano::VirtualPianoPane::new(),
|
||||
landscape_keys: false,
|
||||
lp_press_time: None,
|
||||
lp_press_pos: egui::Pos2::ZERO,
|
||||
editing_index: None,
|
||||
editing_orig_dur: 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -368,6 +388,22 @@ impl PianoRollPane {
|
||||
rect: Rect,
|
||||
shared: &mut SharedPaneState,
|
||||
) {
|
||||
// Landscape mobile: a Keys/Notes toggle bar switches this pane between the full keyboard and
|
||||
// the conventional piano roll. (Portrait uses the keyboard-primary "Synthesia" view below.)
|
||||
let mut rect = rect;
|
||||
if shared.is_mobile && !shared.is_portrait {
|
||||
// Clamp the bar height so a very short pane can't invert the remaining content rect.
|
||||
let bar_h = 30.0_f32.min(rect.height());
|
||||
let bar = Rect::from_min_max(rect.min, pos2(rect.right(), rect.min.y + bar_h));
|
||||
rect = Rect::from_min_max(pos2(rect.left(), bar.bottom()), rect.max);
|
||||
self.render_keys_notes_toggle(ui, bar, shared);
|
||||
if self.landscape_keys {
|
||||
let kb_path: NodePath = Vec::new();
|
||||
self.keyboard.render_content(ui, rect, &kb_path, shared);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let keyboard_rect = Rect::from_min_size(rect.min, vec2(KEYBOARD_WIDTH, rect.height()));
|
||||
let grid_rect = Rect::from_min_max(
|
||||
pos2(rect.min.x + KEYBOARD_WIDTH, rect.min.y),
|
||||
@@ -444,6 +480,13 @@ impl PianoRollPane {
|
||||
}
|
||||
}
|
||||
|
||||
// Mobile portrait: keyboard-primary "Synthesia" instrument surface (keys + falling-notes
|
||||
// roll). Landscape falls through to the conventional horizontal roll (pitch↕ / time▸).
|
||||
if shared.is_mobile && shared.is_portrait {
|
||||
self.render_vertical_mode(ui, rect, shared, &clip_data);
|
||||
return;
|
||||
}
|
||||
|
||||
// Apply quantize if the user changed the snap dropdown (must happen before handle_input
|
||||
// which may clear the selection when the ComboBox click propagates to the grid).
|
||||
if self.snap_user_changed {
|
||||
@@ -556,6 +599,372 @@ impl PianoRollPane {
|
||||
self.render_keyboard(&painter, keyboard_rect);
|
||||
}
|
||||
|
||||
/// Portrait mobile "Synthesia" view — ONE unified instrument surface: an instrument header on
|
||||
/// top, then falling notes as vertical columns (pitch on X, aligned to the keys via the shared
|
||||
/// `KeyboardLayout`, time falling toward the "now" line), then the playable keyboard strip at the
|
||||
/// bottom (reusing the Virtual Piano). Tapping a column adds a note.
|
||||
fn render_vertical_mode(
|
||||
&mut self,
|
||||
ui: &mut egui::Ui,
|
||||
rect: Rect,
|
||||
shared: &mut SharedPaneState,
|
||||
clip_data: &[(u32, f64, f64, f64, Uuid)],
|
||||
) {
|
||||
use super::keyboard_layout::KeyboardLayout;
|
||||
|
||||
// Keyboard-primary layout (portrait, per wireframe Plate 08): the playable keyboard is the
|
||||
// base surface, capped at an ergonomic height. Whether the falling-notes roll appears above
|
||||
// is decided by the shell from the *snapped* pane size-class, so the reveal lands on a stack
|
||||
// snap point (not mid-drag). Short/smallest snap ⇒ keyboard only.
|
||||
const KEY_CAP: f32 = 170.0;
|
||||
let header_h = 32.0;
|
||||
let header_rect = Rect::from_min_max(rect.min, pos2(rect.right(), rect.top() + header_h));
|
||||
let content_top = header_rect.bottom();
|
||||
let content_h = (rect.bottom() - content_top).max(0.0);
|
||||
let show_roll = shared.instrument_show_roll && content_h > KEY_CAP + 40.0;
|
||||
let kb_h = if show_roll { content_h.min(KEY_CAP) } else { content_h };
|
||||
let kb_rect = Rect::from_min_max(pos2(rect.left(), rect.bottom() - kb_h), rect.max);
|
||||
let roll_rect = Rect::from_min_max(pos2(rect.left(), content_top), pos2(rect.right(), kb_rect.top()));
|
||||
|
||||
let pps = self.pixels_per_second; // pixels per second (vertical waterfall)
|
||||
let now_y = roll_rect.bottom(); // a note reaches the keys at its onset time
|
||||
let now = ui.input(|i| i.time);
|
||||
|
||||
// Auto-release a long-press-added preview note once its short audition elapses (the normal
|
||||
// release check lives in handle_input, which the vertical mode bypasses).
|
||||
if let Some(dur) = self.preview_duration {
|
||||
if self.preview_note_sounding && now - self.preview_start_time >= dur {
|
||||
self.preview_note_off(shared);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle roll gestures BEFORE building the layout / drawing, so the roll and the keyboard both
|
||||
// use the updated pan + playhead this same frame (no 1-frame follow lag between them).
|
||||
let resp = if show_roll {
|
||||
let r = ui.interact(roll_rect, ui.id().with("pr_vertical"), egui::Sense::click_and_drag());
|
||||
if self.creating_note.is_none() && r.dragged() {
|
||||
let d = r.drag_delta();
|
||||
if d.y.abs() > 0.0 {
|
||||
// Drag down ⇒ advance time (content follows the finger).
|
||||
let nt = (*shared.playback_time + (d.y / pps) as f64).max(0.0);
|
||||
*shared.playback_time = nt;
|
||||
if let Some(ctrl) = shared.audio_controller.as_ref() {
|
||||
if let Ok(mut c) = ctrl.lock() {
|
||||
c.seek(nt);
|
||||
}
|
||||
}
|
||||
}
|
||||
*shared.keyboard_pan_x += d.x;
|
||||
}
|
||||
Some(r)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let layout = KeyboardLayout::from_width(rect.min.x, rect.width(), *shared.keyboard_octave, *shared.keyboard_pan_x);
|
||||
// Note times are in beats; the playhead is in seconds — convert via the tempo map so the
|
||||
// waterfall lines up with real playback (onset crosses the now line exactly when it sounds).
|
||||
let tempo_map = shared.action_executor.document().tempo_map().clone();
|
||||
let playhead = *shared.playback_time; // seconds
|
||||
|
||||
if let Some(resp) = resp {
|
||||
let painter = ui.painter_at(roll_rect);
|
||||
let bg = shared.theme.bg_color(&["#piano-roll", ".pane-content"], ui.ctx(), Color32::from_rgb(30, 30, 35));
|
||||
painter.rect_filled(roll_rect, 0.0, bg);
|
||||
|
||||
// Column guides aligned to the keys: black-key columns tinted, white-key boundaries lined.
|
||||
for note in layout.visible_notes() {
|
||||
let x = layout.note_x(note);
|
||||
if KeyboardLayout::is_black_key(note) {
|
||||
let w = layout.note_width(note);
|
||||
painter.rect_filled(
|
||||
Rect::from_min_size(pos2(x, roll_rect.min.y), vec2(w, roll_rect.height())),
|
||||
0.0,
|
||||
Color32::from_rgba_unmultiplied(0, 0, 0, 40),
|
||||
);
|
||||
} else {
|
||||
painter.line_segment([pos2(x, roll_rect.min.y), pos2(x, roll_rect.max.y)], Stroke::new(1.0, Color32::from_gray(55)));
|
||||
}
|
||||
}
|
||||
|
||||
// Notes of the selected clip, falling toward the now line.
|
||||
if let Some(clip_id) = self.selected_clip_id {
|
||||
if let Some(&(_, timeline_start, trim_start, duration, _)) =
|
||||
clip_data.iter().find(|c| c.0 == clip_id)
|
||||
{
|
||||
if let Some(events) = shared.midi_event_cache.get(&clip_id) {
|
||||
let resolved = Self::resolve_notes(events);
|
||||
for (ni, note) in resolved.iter().enumerate() {
|
||||
// The note being resized is drawn separately (live) as the temp note.
|
||||
if Some(ni) == self.editing_index {
|
||||
continue;
|
||||
}
|
||||
if note.start_time + note.duration <= trim_start
|
||||
|| note.start_time >= trim_start + duration
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let global = timeline_start + (note.start_time - trim_start);
|
||||
let y_on = now_y - ((tempo_map.transform(global) - playhead) as f32) * pps;
|
||||
let y_off = now_y - ((tempo_map.transform(global + note.duration) - playhead) as f32) * pps;
|
||||
let (top, bot) = (y_on.min(y_off), y_on.max(y_off));
|
||||
if bot < roll_rect.min.y || top > roll_rect.max.y {
|
||||
continue;
|
||||
}
|
||||
let x = layout.note_x(note.note);
|
||||
let w = layout.note_width(note.note).max(3.0);
|
||||
let bright = 0.35 + (note.velocity as f32 / 127.0) * 0.65;
|
||||
let col = Color32::from_rgb(
|
||||
(111.0 * bright) as u8,
|
||||
(220.0 * bright) as u8,
|
||||
(111.0 * bright) as u8,
|
||||
);
|
||||
painter.rect_filled(
|
||||
Rect::from_min_max(
|
||||
pos2(x + 1.0, top.max(roll_rect.min.y)),
|
||||
pos2(x + w - 1.0, bot.min(roll_rect.max.y)),
|
||||
),
|
||||
2.0,
|
||||
col,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The note currently being created (long-press to start, drag along Y to size).
|
||||
if let Some(temp) = self.creating_note.as_ref() {
|
||||
if let Some(&(_, ts, trim, _d, _)) =
|
||||
clip_data.iter().find(|c| Some(c.0) == self.selected_clip_id)
|
||||
{
|
||||
let g = ts + (temp.start_time - trim);
|
||||
let y_on = now_y - ((tempo_map.transform(g) - playhead) as f32) * pps;
|
||||
let y_off = now_y - ((tempo_map.transform(g + temp.duration) - playhead) as f32) * pps;
|
||||
let x = layout.note_x(temp.note);
|
||||
let w = layout.note_width(temp.note).max(3.0);
|
||||
painter.rect_filled(
|
||||
Rect::from_min_max(pos2(x + 1.0, y_on.min(y_off)), pos2(x + w - 1.0, y_on.max(y_off))),
|
||||
2.0,
|
||||
Color32::from_rgb(150, 255, 150),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// The amber "now" line at the boundary with the keyboard.
|
||||
painter.line_segment(
|
||||
[pos2(roll_rect.min.x, now_y), pos2(roll_rect.max.x, now_y)],
|
||||
Stroke::new(2.0, Color32::from_rgb(0xf4, 0xa3, 0x40)),
|
||||
);
|
||||
|
||||
const LONG_PRESS_SECS: f64 = 0.4;
|
||||
let pressed = ui.input(|i| i.pointer.primary_pressed());
|
||||
let down = ui.input(|i| i.pointer.any_down());
|
||||
let ptr = ui.input(|i| i.pointer.latest_pos());
|
||||
|
||||
if self.creating_note.is_some() {
|
||||
// Sizing the note (new or existing): drag along Y sets its duration; release commits.
|
||||
if down {
|
||||
if let (Some(p), Some(&(_, ts, trim, _d, _))) = (
|
||||
ptr,
|
||||
clip_data.iter().find(|c| Some(c.0) == self.selected_clip_id),
|
||||
) {
|
||||
let end_sec = playhead + ((now_y - p.y) / pps) as f64;
|
||||
let end_beats = tempo_map.inverse_transform(end_sec).max(0.0);
|
||||
let end_local = trim + (end_beats - ts);
|
||||
if let Some(t) = self.creating_note.as_mut() {
|
||||
t.duration = (end_local - t.start_time).max(0.25);
|
||||
}
|
||||
}
|
||||
} else if let (Some(temp), Some(clip_id)) =
|
||||
(self.creating_note.take(), self.selected_clip_id)
|
||||
{
|
||||
if let Some(idx) = self.editing_index.take() {
|
||||
let dt = temp.duration - self.editing_orig_dur;
|
||||
self.commit_resize_note(clip_id, idx, dt, shared, clip_data);
|
||||
} else {
|
||||
self.commit_create_note(clip_id, temp, shared, clip_data);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Snap the pan to the nearest key on release.
|
||||
if resp.drag_stopped() {
|
||||
*shared.keyboard_pan_x = layout.snap_pan(*shared.keyboard_pan_x);
|
||||
}
|
||||
// Manual long-press (mouse-hold or touch): armed only on a *fresh* press, and cancelled
|
||||
// for the rest of that press once it moves (→ pan), so pausing mid-pan won't fire.
|
||||
if pressed {
|
||||
match ptr {
|
||||
Some(p) if roll_rect.contains(p) => {
|
||||
self.lp_press_time = Some(now);
|
||||
self.lp_press_pos = p;
|
||||
}
|
||||
_ => self.lp_press_time = None,
|
||||
}
|
||||
}
|
||||
if !down {
|
||||
self.lp_press_time = None;
|
||||
}
|
||||
if let Some(t0) = self.lp_press_time {
|
||||
let moved = ptr.map_or(0.0, |p| (p - self.lp_press_pos).length());
|
||||
if moved > 8.0 {
|
||||
self.lp_press_time = None; // became a pan → suppress for this press
|
||||
} else if now - t0 >= LONG_PRESS_SECS {
|
||||
self.lp_press_time = None;
|
||||
let pos = self.lp_press_pos;
|
||||
if let Some(clip_id) = self.selected_clip_id {
|
||||
if let Some(&(_, timeline_start, trim_start, clip_dur, _)) =
|
||||
clip_data.iter().find(|c| c.0 == clip_id)
|
||||
{
|
||||
let pitch = layout.x_to_note(pos.x);
|
||||
// Hit-test an existing note in this column → resize it; else create.
|
||||
let mut hit = None;
|
||||
if let Some(events) = shared.midi_event_cache.get(&clip_id) {
|
||||
for (i, n) in Self::resolve_notes(events).iter().enumerate() {
|
||||
if n.note != pitch
|
||||
|| n.start_time < trim_start
|
||||
|| n.start_time >= trim_start + clip_dur
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let g = timeline_start + (n.start_time - trim_start);
|
||||
let y_on = now_y - ((tempo_map.transform(g) - playhead) as f32) * pps;
|
||||
let y_off = now_y - ((tempo_map.transform(g + n.duration) - playhead) as f32) * pps;
|
||||
if pos.y >= y_on.min(y_off) && pos.y <= y_on.max(y_off) {
|
||||
hit = Some((i, n.start_time, n.duration, n.velocity));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((idx, onset, dur, vel)) = hit {
|
||||
self.editing_index = Some(idx);
|
||||
self.editing_orig_dur = dur;
|
||||
self.creating_note = Some(TempNote { note: pitch, start_time: onset, duration: dur, velocity: vel });
|
||||
} else {
|
||||
let onset_sec = playhead + ((now_y - pos.y) / pps) as f64;
|
||||
let onset_beats = tempo_map.inverse_transform(onset_sec).max(0.0);
|
||||
let onset_local = snap_to_value((trim_start + (onset_beats - timeline_start)).max(0.0), self.snap_value, &tempo_map);
|
||||
self.editing_index = None;
|
||||
self.creating_note = Some(TempNote { note: pitch, start_time: onset_local, duration: 0.5, velocity: DEFAULT_VELOCITY });
|
||||
}
|
||||
self.preview_note_on(pitch, DEFAULT_VELOCITY, Some(0.4), now, shared);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notes sounding at the playhead → drive the keyboard's highlights so it colors them exactly
|
||||
// like pressed keys (full key, correct white/black layering) rather than an after-overlay.
|
||||
let mut sounding = std::collections::HashSet::new();
|
||||
if let Some(clip_id) = self.selected_clip_id {
|
||||
if let Some(&(_, timeline_start, trim_start, duration, _)) =
|
||||
clip_data.iter().find(|c| c.0 == clip_id)
|
||||
{
|
||||
if let Some(events) = shared.midi_event_cache.get(&clip_id) {
|
||||
for note in Self::resolve_notes(events) {
|
||||
if note.start_time < trim_start || note.start_time >= trim_start + duration {
|
||||
continue;
|
||||
}
|
||||
let global = timeline_start + (note.start_time - trim_start);
|
||||
let s = tempo_map.transform(global);
|
||||
let e = tempo_map.transform(global + note.duration);
|
||||
if playhead >= s && playhead < e {
|
||||
sounding.insert(note.note);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.keyboard.playback_notes = sounding;
|
||||
|
||||
// Instrument header (in this pane's own header) + the always-present playable keyboard strip.
|
||||
self.render_instrument_header(ui, header_rect, shared);
|
||||
let kb_path: NodePath = Vec::new();
|
||||
self.keyboard.render_content(ui, kb_rect, &kb_path, shared);
|
||||
}
|
||||
|
||||
/// The in-pane instrument header: active track name + Presets + REC.
|
||||
fn render_instrument_header(&mut self, ui: &mut egui::Ui, rect: Rect, shared: &mut SharedPaneState) {
|
||||
let painter = ui.painter_at(rect);
|
||||
let hdr = shared.theme.bg_color(&[".pane-header"], ui.ctx(), Color32::from_rgb(24, 24, 28));
|
||||
painter.rect_filled(rect, 0.0, hdr);
|
||||
painter.line_segment(
|
||||
[pos2(rect.left(), rect.bottom()), pos2(rect.right(), rect.bottom())],
|
||||
Stroke::new(1.0, Color32::from_gray(60)),
|
||||
);
|
||||
|
||||
let name = shared
|
||||
.active_layer_id
|
||||
.and_then(|id| shared.action_executor.document().get_layer(&id))
|
||||
.map(|l| l.name().to_string())
|
||||
.unwrap_or_else(|| "No instrument".to_string());
|
||||
painter.text(
|
||||
pos2(rect.left() + 12.0, rect.center().y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
name,
|
||||
egui::FontId::proportional(14.0),
|
||||
Color32::from_gray(220),
|
||||
);
|
||||
|
||||
// REC (rightmost).
|
||||
let rec = Rect::from_min_max(pos2(rect.right() - 64.0, rect.top() + 4.0), pos2(rect.right() - 8.0, rect.bottom() - 4.0));
|
||||
let rec_resp = ui.interact(rec, ui.id().with("pr_rec"), egui::Sense::click());
|
||||
let recording = *shared.is_recording;
|
||||
let rec_bg = if recording { Color32::from_rgb(0xe0, 0x3a, 0x3a) } else { Color32::from_gray(66) };
|
||||
painter.rect_filled(rec, 6.0, rec_bg);
|
||||
painter.circle_filled(pos2(rec.left() + 13.0, rec.center().y), 4.0, Color32::from_rgb(255, 96, 96));
|
||||
painter.text(pos2(rec.left() + 23.0, rec.center().y), egui::Align2::LEFT_CENTER, "REC", egui::FontId::proportional(12.0), Color32::WHITE);
|
||||
if rec_resp.clicked() {
|
||||
*shared.pending_record_toggle = true;
|
||||
}
|
||||
|
||||
// Presets (left of REC).
|
||||
let pre = Rect::from_min_max(pos2(rec.left() - 84.0, rect.top() + 4.0), pos2(rec.left() - 8.0, rect.bottom() - 4.0));
|
||||
let pre_resp = ui.interact(pre, ui.id().with("pr_presets"), egui::Sense::click());
|
||||
painter.rect_filled(pre, 6.0, if pre_resp.hovered() { Color32::from_gray(56) } else { Color32::from_gray(42) });
|
||||
painter.text(pre.center(), egui::Align2::CENTER_CENTER, "Presets", egui::FontId::proportional(12.0), Color32::from_gray(220));
|
||||
if pre_resp.clicked() {
|
||||
*shared.open_instrument_browser = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Landscape Keys/Notes segmented toggle drawn in `bar` (updates `self.landscape_keys`).
|
||||
fn render_keys_notes_toggle(&mut self, ui: &mut egui::Ui, bar: Rect, shared: &mut SharedPaneState) {
|
||||
let painter = ui.painter_at(bar);
|
||||
let bg = shared.theme.bg_color(&[".pane-header"], ui.ctx(), Color32::from_rgb(24, 24, 28));
|
||||
painter.rect_filled(bar, 0.0, bg);
|
||||
painter.line_segment(
|
||||
[pos2(bar.left(), bar.bottom()), pos2(bar.right(), bar.bottom())],
|
||||
Stroke::new(1.0, Color32::from_gray(60)),
|
||||
);
|
||||
|
||||
let seg_w = 74.0;
|
||||
let x0 = bar.center().x - seg_w;
|
||||
let keys_rect = Rect::from_min_size(pos2(x0, bar.top() + 4.0), vec2(seg_w, bar.height() - 8.0));
|
||||
let notes_rect = Rect::from_min_size(pos2(x0 + seg_w, bar.top() + 4.0), vec2(seg_w, bar.height() - 8.0));
|
||||
if ui.interact(keys_rect, ui.id().with("pr_kn_keys"), egui::Sense::click()).clicked() {
|
||||
self.landscape_keys = true;
|
||||
}
|
||||
if ui.interact(notes_rect, ui.id().with("pr_kn_notes"), egui::Sense::click()).clicked() {
|
||||
self.landscape_keys = false;
|
||||
}
|
||||
let accent = Color32::from_rgb(0x4a, 0xa3, 0xff);
|
||||
for (r, label, on) in [
|
||||
(keys_rect, "Keys", self.landscape_keys),
|
||||
(notes_rect, "Notes", !self.landscape_keys),
|
||||
] {
|
||||
painter.rect_filled(r, 6.0, if on { accent } else { Color32::from_gray(46) });
|
||||
painter.text(
|
||||
r.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
label,
|
||||
egui::FontId::proportional(13.0),
|
||||
if on { Color32::WHITE } else { Color32::from_gray(200) },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn render_keyboard(&self, painter: &egui::Painter, rect: Rect) {
|
||||
// Background
|
||||
painter.rect_filled(rect, 0.0, Color32::from_rgb(40, 40, 45));
|
||||
|
||||
@@ -50,3 +50,34 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
a
|
||||
);
|
||||
}
|
||||
|
||||
// Highlight rolloff: identity below the knee, then a smooth C1 rolloff that maps [knee, ∞) → [knee, 1)
|
||||
// so super-white (HDR) detail is recovered instead of hard-clipped. SDR below the knee is untouched.
|
||||
fn highlight_rolloff(x: f32) -> f32 {
|
||||
let knee = 0.8;
|
||||
if x <= knee {
|
||||
return x;
|
||||
}
|
||||
let headroom = 1.0 - knee;
|
||||
return knee + headroom * (1.0 - exp(-(x - knee) / headroom));
|
||||
}
|
||||
|
||||
// Variant of fs_main with highlight rolloff (document HDR output mode = Highlight rolloff).
|
||||
@fragment
|
||||
fn fs_main_rolloff(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let linear = textureSample(input_tex, input_sampler, in.uv);
|
||||
let a = linear.a;
|
||||
let straight = select(linear.rgb / a, vec3<f32>(0.0), a <= 0.0);
|
||||
let rolled = vec3<f32>(
|
||||
highlight_rolloff(straight.r),
|
||||
highlight_rolloff(straight.g),
|
||||
highlight_rolloff(straight.b),
|
||||
);
|
||||
|
||||
return vec4<f32>(
|
||||
linear_to_srgb_channel(rolled.r),
|
||||
linear_to_srgb_channel(rolled.g),
|
||||
linear_to_srgb_channel(rolled.b),
|
||||
a
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// NV12 → linear-RGB blit shader.
|
||||
//
|
||||
// Samples a hardware-decoded video frame stored as two planes — Y (R8Unorm) and
|
||||
// interleaved CbCr (Rg8Unorm, half-res) — converts BT.709 Y'CbCr → gamma-encoded
|
||||
// R'G'B', then sRGB→linear, and writes straight-alpha linear into the Rgba16Float
|
||||
// HDR layer. This mirrors the software path (swscale → sRGB RGBA8 → sampled as
|
||||
// Rgba8UnormSrgb → linear) so hardware- and software-decoded video match.
|
||||
//
|
||||
// The affine transform (viewport UV → frame UV) is the same packing as
|
||||
// canvas_blit.wgsl's BlitTransform; `full_range` selects full vs. studio-swing
|
||||
// de-quantization.
|
||||
|
||||
struct Nv12Params {
|
||||
col0: vec4<f32>,
|
||||
col1: vec4<f32>,
|
||||
col2: vec4<f32>,
|
||||
// Y'CbCr→R'G'B' matrix from the source colorspace: [Cr→R, Cb→G, Cr→G, Cb→B].
|
||||
coeffs: vec4<f32>,
|
||||
// .x = full_range; .y = transfer (0 gamma, 1 PQ, 2 HLG); .z = primaries (0 BT.709, 1 BT.2020).
|
||||
// A vec4 keeps each block 16-aligned and the struct 80 bytes (Rust `[f32;4] + u32 + [u32;3]`).
|
||||
flags: vec4<u32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var y_tex: texture_2d<f32>;
|
||||
@group(0) @binding(1) var samp: sampler;
|
||||
@group(0) @binding(2) var<uniform> params: Nv12Params;
|
||||
@group(0) @binding(3) var uv_tex: texture_2d<f32>;
|
||||
|
||||
struct VertexOutput {
|
||||
@builtin(position) position: vec4<f32>,
|
||||
@location(0) uv: vec2<f32>,
|
||||
}
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
var out: VertexOutput;
|
||||
let x = f32((vertex_index & 1u) << 1u);
|
||||
let y = f32(vertex_index & 2u);
|
||||
out.position = vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
|
||||
out.uv = vec2<f32>(x, y);
|
||||
return out;
|
||||
}
|
||||
|
||||
fn srgb_to_linear(c: vec3<f32>) -> vec3<f32> {
|
||||
let lo = c / 12.92;
|
||||
let hi = pow((c + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4));
|
||||
return select(lo, hi, c > vec3<f32>(0.04045));
|
||||
}
|
||||
|
||||
// SMPTE ST 2084 (PQ) EOTF: encoded [0,1] → absolute luminance, then normalize so the 203-nit
|
||||
// graphics white = 1.0 (HDR highlights exceed 1.0). Per-channel.
|
||||
fn pq_to_linear(c: vec3<f32>) -> vec3<f32> {
|
||||
let m1 = 0.1593017578125;
|
||||
let m2 = 78.84375;
|
||||
let c1 = 0.8359375;
|
||||
let c2 = 18.8515625;
|
||||
let c3 = 18.6875;
|
||||
let e = pow(max(c, vec3<f32>(0.0)), vec3<f32>(1.0 / m2));
|
||||
let num = max(e - vec3<f32>(c1), vec3<f32>(0.0));
|
||||
let den = vec3<f32>(c2) - c3 * e;
|
||||
let nits = pow(num / den, vec3<f32>(1.0 / m1)) * 10000.0; // 0..10000 cd/m²
|
||||
return nits / 203.0;
|
||||
}
|
||||
|
||||
// ARIB STD-B67 (HLG) inverse-OETF → scene light, normalized so reference white (signal 0.75) = 1.0.
|
||||
// The display OOTF is omitted (scene-referred compositing); approximate but reasonable for SDR-out.
|
||||
fn hlg_to_linear(c: vec3<f32>) -> vec3<f32> {
|
||||
let a = 0.17883277;
|
||||
let b = 0.28466892;
|
||||
let cc = 0.55991073;
|
||||
let lo = (c * c) / 3.0;
|
||||
let hi = (exp((c - vec3<f32>(cc)) / a) + vec3<f32>(b)) / 12.0;
|
||||
let scene = select(lo, hi, c > vec3<f32>(0.5));
|
||||
return scene / 0.26496256; // hlg_inv_oetf(0.75): put reference white at 1.0
|
||||
}
|
||||
|
||||
// BT.2020 → BT.709 primaries, linear light (ITU-R BT.2087). Out-of-709 colours go negative → clamp.
|
||||
fn bt2020_to_bt709(c: vec3<f32>) -> vec3<f32> {
|
||||
let r = 1.660491 * c.r - 0.587641 * c.g - 0.072850 * c.b;
|
||||
let g = -0.124550 * c.r + 1.132900 * c.g - 0.008349 * c.b;
|
||||
let b = -0.018151 * c.r - 0.100579 * c.g + 1.118730 * c.b;
|
||||
return max(vec3<f32>(r, g, b), vec3<f32>(0.0));
|
||||
}
|
||||
|
||||
@fragment
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let m = mat3x3<f32>(params.col0.xyz, params.col1.xyz, params.col2.xyz);
|
||||
let frame_uv = (m * vec3<f32>(in.uv.x, in.uv.y, 1.0)).xy;
|
||||
|
||||
if frame_uv.x < 0.0 || frame_uv.x > 1.0
|
||||
|| frame_uv.y < 0.0 || frame_uv.y > 1.0 {
|
||||
return vec4<f32>(0.0, 0.0, 0.0, 0.0);
|
||||
}
|
||||
|
||||
let yv = textureSample(y_tex, samp, frame_uv).r;
|
||||
let cbcr = textureSample(uv_tex, samp, frame_uv).rg;
|
||||
|
||||
var Y: f32;
|
||||
var Cb: f32;
|
||||
var Cr: f32;
|
||||
if params.flags.x != 0u {
|
||||
// Full ("JPEG") range: [0,255] luma, chroma centered at 128.
|
||||
Y = yv;
|
||||
Cb = cbcr.r - 0.5;
|
||||
Cr = cbcr.g - 0.5;
|
||||
} else {
|
||||
// Studio swing: Y'∈[16,235], Cb/Cr∈[16,240].
|
||||
Y = (yv * 255.0 - 16.0) / 219.0;
|
||||
Cb = (cbcr.r * 255.0 - 128.0) / 224.0;
|
||||
Cr = (cbcr.g * 255.0 - 128.0) / 224.0;
|
||||
}
|
||||
|
||||
// Y'CbCr → gamma-encoded R'G'B' using the source colorspace's matrix.
|
||||
let r = Y + params.coeffs.x * Cr;
|
||||
let g = Y + params.coeffs.y * Cb + params.coeffs.z * Cr;
|
||||
let b = Y + params.coeffs.w * Cb;
|
||||
// Valid encoded signal is [0,1]; clamp before the EOTF (HDR comes from the EOTF, not overshoot).
|
||||
let rgb_enc = clamp(vec3<f32>(r, g, b), vec3<f32>(0.0), vec3<f32>(1.0));
|
||||
|
||||
// Encoded R'G'B' → scene-linear (graphics white = 1.0; HDR may exceed 1.0).
|
||||
var rgb_lin: vec3<f32>;
|
||||
if params.flags.y == 1u {
|
||||
rgb_lin = pq_to_linear(rgb_enc);
|
||||
} else if params.flags.y == 2u {
|
||||
rgb_lin = hlg_to_linear(rgb_enc);
|
||||
} else {
|
||||
rgb_lin = srgb_to_linear(rgb_enc);
|
||||
}
|
||||
|
||||
// Wide-gamut → BT.709 in linear light to match the compositor's primaries.
|
||||
if params.flags.z == 1u {
|
||||
rgb_lin = bt2020_to_bt709(rgb_lin);
|
||||
}
|
||||
|
||||
return vec4<f32>(rgb_lin, 1.0);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -17,6 +17,8 @@ use std::collections::HashMap;
|
||||
const RULER_HEIGHT: f32 = 30.0;
|
||||
const LAYER_HEIGHT: f32 = 60.0;
|
||||
const LAYER_HEADER_WIDTH: f32 = 200.0;
|
||||
/// On mobile the header collapses to a minimal color swatch with a 1:2 width:height aspect.
|
||||
const MOBILE_LAYER_HEADER_WIDTH: f32 = LAYER_HEIGHT * 0.5;
|
||||
const MIN_PIXELS_PER_SECOND: f32 = 1.0; // Allow zooming out to see 10+ minutes
|
||||
const MAX_PIXELS_PER_SECOND: f32 = 500.0;
|
||||
const EDGE_DETECTION_PIXELS: f32 = 8.0; // Distance from edge to detect trim handles
|
||||
@@ -212,6 +214,7 @@ fn effective_clip_duration(
|
||||
AnyLayer::Effect(_) => Some(lightningbeam_core::effect::EFFECT_DURATION),
|
||||
AnyLayer::Group(_) => None,
|
||||
AnyLayer::Raster(_) => None,
|
||||
AnyLayer::Text(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,6 +268,9 @@ pub struct TimelinePane {
|
||||
/// Is the user panning the timeline?
|
||||
is_panning: bool,
|
||||
last_pan_pos: Option<egui::Pos2>,
|
||||
/// Manual long-press tracking for the mobile context menu: press start time + position.
|
||||
lp_time: Option<f64>,
|
||||
lp_pos: egui::Pos2,
|
||||
|
||||
/// Clip drag state (None if not dragging)
|
||||
clip_drag_state: Option<ClipDragType>,
|
||||
@@ -685,6 +691,7 @@ fn layer_clips<'a>(
|
||||
AnyLayer::Effect(l) => &l.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -718,6 +725,7 @@ fn collect_clip_instances<'a>(
|
||||
}
|
||||
}
|
||||
AnyLayer::Raster(_) => {}
|
||||
AnyLayer::Text(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -768,6 +776,7 @@ fn layer_type_info(layer: &AnyLayer) -> (&'static str, egui::Color32) {
|
||||
AnyLayer::Effect(_) => ("Effect", egui::Color32::from_rgb(255, 100, 180)),
|
||||
AnyLayer::Group(_) => ("Group", egui::Color32::from_rgb(0, 180, 180)),
|
||||
AnyLayer::Raster(_) => ("Raster", egui::Color32::from_rgb(160, 100, 200)),
|
||||
AnyLayer::Text(_) => ("Text", egui::Color32::from_rgb(220, 200, 120)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -782,6 +791,8 @@ impl TimelinePane {
|
||||
is_scrubbing: false,
|
||||
is_panning: false,
|
||||
last_pan_pos: None,
|
||||
lp_time: None,
|
||||
lp_pos: egui::Pos2::ZERO,
|
||||
clip_drag_state: None,
|
||||
drag_offset: 0.0,
|
||||
drag_anchor_start: 0.0,
|
||||
@@ -945,7 +956,7 @@ impl TimelinePane {
|
||||
|
||||
/// Toggle recording on/off
|
||||
/// In Auto mode, records to the active layer (audio or video with camera)
|
||||
fn toggle_recording(&mut self, shared: &mut SharedPaneState) {
|
||||
pub(crate) fn toggle_recording(&mut self, shared: &mut SharedPaneState) {
|
||||
if *shared.is_recording {
|
||||
// Stop recording
|
||||
self.stop_recording(shared);
|
||||
@@ -1206,7 +1217,7 @@ impl TimelinePane {
|
||||
|
||||
/// Stop all active recordings
|
||||
/// Called every frame; fires deferred recording commands once the count-in pre-roll ends.
|
||||
fn check_pending_recording_start(&mut self, shared: &mut SharedPaneState) {
|
||||
pub(crate) fn check_pending_recording_start(&mut self, shared: &mut SharedPaneState) {
|
||||
let Some(ref pending) = self.pending_recording_start else { return };
|
||||
if !*shared.is_playing || *shared.playback_time < pending.trigger_time {
|
||||
return;
|
||||
@@ -1226,7 +1237,7 @@ impl TimelinePane {
|
||||
*shared.count_in_enabled = saved_count_in;
|
||||
}
|
||||
|
||||
fn stop_recording(&mut self, shared: &mut SharedPaneState) {
|
||||
pub(crate) fn stop_recording(&mut self, shared: &mut SharedPaneState) {
|
||||
// Cancel any in-progress count-in
|
||||
self.pending_recording_start = None;
|
||||
|
||||
@@ -1475,6 +1486,15 @@ impl TimelinePane {
|
||||
self.pixels_per_second = 100.0;
|
||||
}
|
||||
|
||||
/// Fit the whole project duration into the given content width, scrolled to the start.
|
||||
/// (Gesture P5-2: double-tap empty → zoom-to-fit.)
|
||||
pub fn fit_to_project(&mut self, viewport_width: f32) {
|
||||
let dur = self.duration.max(0.01);
|
||||
self.pixels_per_second =
|
||||
(viewport_width / dur as f32).clamp(MIN_PIXELS_PER_SECOND, MAX_PIXELS_PER_SECOND);
|
||||
self.viewport_start_time = 0.0;
|
||||
}
|
||||
|
||||
/// Apply zoom while keeping the time under the cursor stationary
|
||||
fn apply_zoom_at_point(&mut self, zoom_delta: f32, mouse_x: f32) {
|
||||
let old_zoom = self.pixels_per_second;
|
||||
@@ -1933,6 +1953,8 @@ impl TimelinePane {
|
||||
track_levels: &std::collections::HashMap<daw_backend::TrackId, f32>,
|
||||
input_level: f32,
|
||||
playback_time: f64,
|
||||
header_width: f32,
|
||||
is_mobile: bool,
|
||||
) {
|
||||
// Background for header column
|
||||
let header_style = theme.style(".timeline-header", ui.ctx());
|
||||
@@ -1995,7 +2017,7 @@ impl TimelinePane {
|
||||
|
||||
let header_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.min.x, y),
|
||||
egui::vec2(LAYER_HEADER_WIDTH, LAYER_HEIGHT),
|
||||
egui::vec2(header_width, LAYER_HEIGHT),
|
||||
);
|
||||
|
||||
// Determine the AnyLayer or GroupLayer for this row
|
||||
@@ -2029,6 +2051,27 @@ impl TimelinePane {
|
||||
|
||||
ui.painter().rect_filled(header_rect, 0.0, bg_color);
|
||||
|
||||
// Mobile: collapse the header to a minimal color swatch (1:2 w:h). Selection is handled
|
||||
// by handle_input via the (narrow) header rect, so we only draw here.
|
||||
if is_mobile {
|
||||
let sw = header_rect.shrink(2.0);
|
||||
let col = if is_active || is_selected {
|
||||
type_color
|
||||
} else {
|
||||
type_color.gamma_multiply(0.55)
|
||||
};
|
||||
ui.painter().rect_filled(sw, 3.0, col);
|
||||
if is_active || is_selected {
|
||||
ui.painter().rect_stroke(
|
||||
sw,
|
||||
3.0,
|
||||
egui::Stroke::new(1.5, egui::Color32::WHITE),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Gutter area (left of indicator) — solid group color, with collapse chevron
|
||||
if indent > 0.0 {
|
||||
let gutter_rect = egui::Rect::from_min_size(
|
||||
@@ -4935,29 +4978,40 @@ impl TimelinePane {
|
||||
// Only handle scroll when mouse is over the timeline area
|
||||
let mut handled = false;
|
||||
let pointer_over_timeline = response.hovered() || ui.rect_contains_pointer(header_rect);
|
||||
|
||||
// Unified pinch / Ctrl+scroll time-zoom: `zoom_delta()` folds in touch-pinch (on device) AND
|
||||
// Ctrl+wheel/trackpad (on desktop). Multiplicative factor (1.0 = no change); apply_zoom_at_point
|
||||
// wants an additive delta. This is the single path for factor-zoom — the raw MouseWheel branch
|
||||
// below only handles plain (non-Ctrl) mouse-wheel zoom and non-Ctrl trackpad pan.
|
||||
if pointer_over_timeline {
|
||||
let zoom_factor = ui.input(|i| i.zoom_delta());
|
||||
if (zoom_factor - 1.0).abs() > f32::EPSILON {
|
||||
let center_x = ui
|
||||
.input(|i| i.multi_touch().map(|m| m.center_pos.x))
|
||||
.map(|x| x - content_rect.min.x)
|
||||
.unwrap_or(mouse_x);
|
||||
self.apply_zoom_at_point(zoom_factor - 1.0, center_x);
|
||||
}
|
||||
}
|
||||
|
||||
if pointer_over_timeline { ui.input(|i| {
|
||||
for event in &i.raw.events {
|
||||
if let egui::Event::MouseWheel { unit, delta, modifiers, .. } = event {
|
||||
match unit {
|
||||
egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => {
|
||||
// Real mouse wheel (discrete clicks) -> always zoom horizontally
|
||||
let zoom_delta = if ctrl_held || modifiers.ctrl {
|
||||
delta.y * 0.01 // Ctrl+wheel: faster zoom
|
||||
} else {
|
||||
delta.y * 0.005 // Normal zoom
|
||||
};
|
||||
self.apply_zoom_at_point(zoom_delta, mouse_x);
|
||||
// Plain mouse wheel zooms; Ctrl+wheel handled above via zoom_delta().
|
||||
// Consume the event either way so the pan fallback doesn't also fire.
|
||||
if !(ctrl_held || modifiers.ctrl) {
|
||||
self.apply_zoom_at_point(delta.y * 0.005, mouse_x);
|
||||
}
|
||||
handled = true;
|
||||
}
|
||||
egui::MouseWheelUnit::Point => {
|
||||
// Trackpad (smooth scrolling)
|
||||
// Trackpad: Ctrl-zoom handled above (consume it); non-Ctrl falls through
|
||||
// to scroll_delta panning below.
|
||||
if ctrl_held || modifiers.ctrl {
|
||||
// Ctrl held: zoom
|
||||
let zoom_delta = delta.y * 0.005;
|
||||
self.apply_zoom_at_point(zoom_delta, mouse_x);
|
||||
handled = true;
|
||||
}
|
||||
// Otherwise let scroll_delta handle panning (below)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5000,6 +5054,18 @@ impl TimelinePane {
|
||||
}
|
||||
}
|
||||
|
||||
// Double-tap / double-click on empty space → fit the whole project into view. (Gesture P5-2.)
|
||||
if response.double_clicked() {
|
||||
if let Some(pos) = response.interact_pointer_pos() {
|
||||
let over_clip = self
|
||||
.detect_clip_at_pointer(pos, document, content_rect, header_rect, editing_clip_id, &audio_cache)
|
||||
.is_some();
|
||||
if !over_clip {
|
||||
self.fit_to_project(content_rect.width());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update cursor based on hover position (only if not scrubbing or panning)
|
||||
if !self.is_scrubbing && !self.is_panning {
|
||||
// If dragging a clip with trim/loop, keep the appropriate cursor
|
||||
@@ -5452,15 +5518,21 @@ impl PaneRenderer for TimelinePane {
|
||||
}
|
||||
self.duration = max_endpoint;
|
||||
|
||||
// Split into layer header column (left) and timeline content (right)
|
||||
// Split into layer header column (left) and timeline content (right). On mobile the header
|
||||
// column collapses to a minimal color-swatch width.
|
||||
let header_width = if shared.is_mobile {
|
||||
MOBILE_LAYER_HEADER_WIDTH
|
||||
} else {
|
||||
LAYER_HEADER_WIDTH
|
||||
};
|
||||
let header_column_rect = egui::Rect::from_min_size(
|
||||
rect.min,
|
||||
egui::vec2(LAYER_HEADER_WIDTH, rect.height()),
|
||||
egui::vec2(header_width, rect.height()),
|
||||
);
|
||||
|
||||
let timeline_rect = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(LAYER_HEADER_WIDTH, 0.0),
|
||||
egui::vec2(rect.width() - LAYER_HEADER_WIDTH, rect.height()),
|
||||
rect.min + egui::vec2(header_width, 0.0),
|
||||
egui::vec2(rect.width() - header_width, rect.height()),
|
||||
);
|
||||
|
||||
// Split timeline into ruler and content areas
|
||||
@@ -5477,12 +5549,12 @@ impl PaneRenderer for TimelinePane {
|
||||
// Split header column into ruler area (top) and layer headers (bottom)
|
||||
let header_ruler_spacer = egui::Rect::from_min_size(
|
||||
header_column_rect.min,
|
||||
egui::vec2(LAYER_HEADER_WIDTH, RULER_HEIGHT),
|
||||
egui::vec2(header_width, RULER_HEIGHT),
|
||||
);
|
||||
|
||||
let layer_headers_rect = egui::Rect::from_min_size(
|
||||
header_column_rect.min + egui::vec2(0.0, RULER_HEIGHT),
|
||||
egui::vec2(LAYER_HEADER_WIDTH, header_column_rect.height() - RULER_HEIGHT),
|
||||
egui::vec2(header_width, header_column_rect.height() - RULER_HEIGHT),
|
||||
);
|
||||
|
||||
// Save original clip rect to restore at the end
|
||||
@@ -5499,7 +5571,7 @@ impl PaneRenderer for TimelinePane {
|
||||
|
||||
// Render layer header column with clipping
|
||||
ui.set_clip_rect(layer_headers_rect.intersect(original_clip_rect));
|
||||
self.render_layer_headers(ui, layer_headers_rect, shared.theme, shared.active_layer_id, shared.focus, &mut shared.pending_actions, document, &context_layers, shared.layer_to_track_map, shared.track_levels, shared.input_level, *shared.playback_time);
|
||||
self.render_layer_headers(ui, layer_headers_rect, shared.theme, shared.active_layer_id, shared.focus, &mut shared.pending_actions, document, &context_layers, shared.layer_to_track_map, shared.track_levels, shared.input_level, *shared.playback_time, header_width, shared.is_mobile);
|
||||
|
||||
// Render time ruler (clip to ruler rect)
|
||||
ui.set_clip_rect(ruler_rect.intersect(original_clip_rect));
|
||||
@@ -5770,9 +5842,10 @@ impl PaneRenderer for TimelinePane {
|
||||
}
|
||||
ui.set_clip_rect(original_clip_rect);
|
||||
|
||||
// Context menu: detect right-click on clips or empty timeline space
|
||||
// Context menu: detect right-click on clips or empty timeline space (desktop only — mobile
|
||||
// uses the long-press menu below).
|
||||
let mut just_opened_menu = false;
|
||||
let secondary_clicked = ui.input(|i| i.pointer.button_clicked(egui::PointerButton::Secondary));
|
||||
let secondary_clicked = !shared.is_mobile && ui.input(|i| i.pointer.button_clicked(egui::PointerButton::Secondary));
|
||||
if secondary_clicked {
|
||||
if let Some(pos) = ui.input(|i| i.pointer.interact_pos()) {
|
||||
if content_rect.contains(pos) {
|
||||
@@ -5792,6 +5865,67 @@ impl PaneRenderer for TimelinePane {
|
||||
}
|
||||
}
|
||||
|
||||
// Mobile: a manual long-press (hold in place ~0.4s) builds a persistent context menu rendered
|
||||
// by the shell — clip actions on a clip, animation (keyframe/tween) actions on an empty lane.
|
||||
let mut long_press: Option<egui::Pos2> = None;
|
||||
if shared.is_mobile {
|
||||
let now = ui.input(|i| i.time);
|
||||
let down = ui.input(|i| i.pointer.any_down());
|
||||
let ptr = ui.input(|i| i.pointer.latest_pos());
|
||||
if ui.input(|i| i.pointer.primary_pressed()) {
|
||||
match ptr {
|
||||
Some(p) if content_rect.contains(p) => {
|
||||
self.lp_time = Some(now);
|
||||
self.lp_pos = p;
|
||||
}
|
||||
_ => self.lp_time = None,
|
||||
}
|
||||
}
|
||||
if !down {
|
||||
self.lp_time = None;
|
||||
}
|
||||
if let Some(t0) = self.lp_time {
|
||||
let moved = ptr.map_or(0.0, |p| (p - self.lp_pos).length());
|
||||
if moved > 8.0 {
|
||||
self.lp_time = None;
|
||||
} else if now - t0 >= 0.4 {
|
||||
self.lp_time = None;
|
||||
long_press = Some(self.lp_pos);
|
||||
} else {
|
||||
// Still counting down — request a repaint so the threshold is re-evaluated even if
|
||||
// the finger is perfectly still and egui would otherwise go idle (no input events).
|
||||
let remaining = (0.4 - (now - t0)).max(0.0);
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(remaining));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(pos) = long_press {
|
||||
use crate::menu::MenuAction;
|
||||
let mut items: Vec<(String, MenuAction)> = Vec::new();
|
||||
if let Some((_drag_type, clip_id)) = self.detect_clip_at_pointer(pos, document, content_rect, layer_headers_rect, editing_clip_id.as_ref(), &audio_cache) {
|
||||
if !shared.selection.contains_clip_instance(&clip_id) {
|
||||
shared.selection.select_only_clip_instance(clip_id);
|
||||
}
|
||||
*shared.focus = lightningbeam_core::selection::FocusSelection::ClipInstances(shared.selection.clip_instances().to_vec());
|
||||
items.push(("Split clip".into(), MenuAction::SplitClip));
|
||||
items.push(("Duplicate clip".into(), MenuAction::DuplicateClip));
|
||||
items.push(("Cut".into(), MenuAction::Cut));
|
||||
items.push(("Copy".into(), MenuAction::Copy));
|
||||
items.push(("Paste".into(), MenuAction::Paste));
|
||||
items.push(("Delete".into(), MenuAction::Delete));
|
||||
} else {
|
||||
items.push(("New keyframe".into(), MenuAction::NewKeyframe));
|
||||
items.push(("New blank keyframe".into(), MenuAction::NewBlankKeyframe));
|
||||
items.push(("Add keyframe at playhead".into(), MenuAction::AddKeyframeAtPlayhead));
|
||||
items.push(("Duplicate keyframe".into(), MenuAction::DuplicateKeyframe));
|
||||
items.push(("Delete frame".into(), MenuAction::DeleteFrame));
|
||||
items.push(("Add motion tween".into(), MenuAction::AddMotionTween));
|
||||
items.push(("Add shape tween".into(), MenuAction::AddShapeTween));
|
||||
items.push(("Paste".into(), MenuAction::Paste));
|
||||
}
|
||||
*shared.mobile_context_menu = Some(crate::panes::MobileContextMenu { pos, items });
|
||||
}
|
||||
|
||||
// Render context menu
|
||||
if let Some((ctx_clip_id, menu_pos)) = self.context_menu_clip {
|
||||
let has_clip = ctx_clip_id.is_some();
|
||||
@@ -6151,20 +6285,11 @@ impl PaneRenderer for TimelinePane {
|
||||
let mut clip_instance = ClipInstance::new(dragging.clip_id)
|
||||
.with_timeline_start(drop_time);
|
||||
|
||||
// For video clips, scale to fill document dimensions
|
||||
// For video clips, fit uniformly + centered (preserve aspect).
|
||||
// Shared with the direct-import path via Transform::fit_centered.
|
||||
if dragging.clip_type == DragClipType::Video {
|
||||
if let Some((video_width, video_height)) = dragging.dimensions {
|
||||
// Calculate scale to fill document
|
||||
let scale_x = doc.width / video_width;
|
||||
let scale_y = doc.height / video_height;
|
||||
|
||||
clip_instance.transform.scale_x = scale_x;
|
||||
clip_instance.transform.scale_y = scale_y;
|
||||
|
||||
// Position at (0, 0) to center the scaled video
|
||||
// (scaled dimensions = document dimensions, so top-left at origin centers it)
|
||||
clip_instance.transform.x = 0.0;
|
||||
clip_instance.transform.y = 0.0;
|
||||
clip_instance.transform.fit_centered(video_width, video_height, doc.width, doc.height);
|
||||
} else {
|
||||
// No dimensions available, use document center
|
||||
clip_instance.transform.x = center_x;
|
||||
|
||||
@@ -43,6 +43,7 @@ impl PaneRenderer for ToolbarPane {
|
||||
AnyLayer::Effect(_) => LayerType::Effect,
|
||||
AnyLayer::Group(_) => LayerType::Group,
|
||||
AnyLayer::Raster(_) => LayerType::Raster,
|
||||
AnyLayer::Text(_) => LayerType::Text,
|
||||
});
|
||||
|
||||
// Auto-switch to Select if the current tool isn't available for this layer type
|
||||
|
||||
@@ -33,6 +33,8 @@ pub struct VirtualPianoPane {
|
||||
sustain_active: bool,
|
||||
/// Notes being held by sustain pedal (not by active key/mouse press)
|
||||
sustained_notes: HashSet<u8>,
|
||||
/// Externally-driven highlights (e.g. notes sounding during playback), colored like pressed keys.
|
||||
pub playback_notes: HashSet<u8>,
|
||||
}
|
||||
|
||||
impl Default for VirtualPianoPane {
|
||||
@@ -83,6 +85,7 @@ impl VirtualPianoPane {
|
||||
note_to_key_map,
|
||||
sustain_active: false,
|
||||
sustained_notes: HashSet::new(),
|
||||
playback_notes: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,9 +219,17 @@ impl VirtualPianoPane {
|
||||
|
||||
/// Render the piano keyboard
|
||||
fn render_keyboard(&mut self, ui: &mut egui::Ui, rect: egui::Rect, shared: &mut SharedPaneState) {
|
||||
// Calculate visible range and key dimensions based on pane size
|
||||
let (visible_start, visible_end, white_key_width, offset_x) =
|
||||
self.calculate_visible_range(rect.width(), rect.height());
|
||||
// Calculate visible range and key dimensions based on pane size. On mobile use the shared
|
||||
// width-driven layout (so the portrait Piano Roll's columns line up with these keys).
|
||||
let (visible_start, visible_end, white_key_width, offset_x) = if shared.is_mobile {
|
||||
let layout = super::keyboard_layout::KeyboardLayout::from_width(
|
||||
rect.min.x, rect.width(), self.octave_offset, *shared.keyboard_pan_x,
|
||||
);
|
||||
let vs = layout.first_visible_white();
|
||||
(vs, layout.last_visible_note(), layout.white_key_width, layout.note_x(vs) - rect.min.x)
|
||||
} else {
|
||||
self.calculate_visible_range(rect.width(), rect.height())
|
||||
};
|
||||
|
||||
let white_key_height = rect.height();
|
||||
let black_key_width = white_key_width * self.black_key_width_ratio;
|
||||
@@ -238,6 +249,11 @@ impl VirtualPianoPane {
|
||||
return;
|
||||
}
|
||||
|
||||
// Only play notes when the press STARTED on the keyboard, so dragging in from the roll above
|
||||
// (mobile) doesn't trigger notes. On desktop the whole pane is the keyboard, so a click here
|
||||
// always qualifies.
|
||||
let started_here = ui.input(|i| i.pointer.press_origin().map_or(false, |p| rect.contains(p)));
|
||||
|
||||
// Count white keys before each note for positioning
|
||||
let mut white_key_positions: std::collections::HashMap<u8, f32> = std::collections::HashMap::new();
|
||||
let mut white_count = 0;
|
||||
@@ -303,7 +319,8 @@ impl VirtualPianoPane {
|
||||
});
|
||||
let pointer_down = ui.input(|i| i.pointer.primary_down());
|
||||
let is_pressed = self.pressed_notes.contains(¬e) ||
|
||||
(!black_key_interacted && pointer_over_key && pointer_down);
|
||||
self.playback_notes.contains(¬e) ||
|
||||
(started_here && !black_key_interacted && pointer_over_key && pointer_down);
|
||||
let color = if is_pressed {
|
||||
shared.theme.bg_color(&[".piano-white-key", ".pressed"], ui.ctx(), egui::Color32::from_rgb(100, 150, 255))
|
||||
} else {
|
||||
@@ -320,8 +337,9 @@ impl VirtualPianoPane {
|
||||
);
|
||||
|
||||
if !black_key_interacted {
|
||||
// Mouse down starts note (detect primary button pressed on this key)
|
||||
if pointer_over_key && ui.input(|i| i.pointer.primary_pressed()) {
|
||||
// Mouse down starts note (detect primary button pressed on this key). Gated on
|
||||
// `started_here` so a drag that began on the roll above doesn't start notes.
|
||||
if started_here && pointer_over_key && ui.input(|i| i.pointer.primary_pressed()) {
|
||||
// Calculate velocity based on mouse Y position
|
||||
let mouse_y = ui.input(|i| i.pointer.hover_pos()).unwrap().y;
|
||||
let velocity = self.calculate_velocity_from_mouse_y(mouse_y, key_rect);
|
||||
@@ -330,7 +348,8 @@ impl VirtualPianoPane {
|
||||
self.dragging_note = Some(note);
|
||||
}
|
||||
|
||||
// Mouse up stops note (detect primary button released)
|
||||
// Mouse up stops note (detect primary button released). NEVER gated — a held note
|
||||
// must always release.
|
||||
if ui.input(|i| i.pointer.primary_released()) {
|
||||
if self.dragging_note == Some(note) {
|
||||
self.send_note_off(note, shared);
|
||||
@@ -339,7 +358,7 @@ impl VirtualPianoPane {
|
||||
}
|
||||
|
||||
// Dragging over a new key (pointer is down and over a different key)
|
||||
if pointer_over_key && pointer_down {
|
||||
if started_here && pointer_over_key && pointer_down {
|
||||
if self.dragging_note != Some(note) {
|
||||
// Stop previous note
|
||||
if let Some(prev_note) = self.dragging_note {
|
||||
@@ -387,7 +406,8 @@ impl VirtualPianoPane {
|
||||
});
|
||||
let pointer_down = ui.input(|i| i.pointer.primary_down());
|
||||
let is_pressed = self.pressed_notes.contains(¬e) ||
|
||||
(pointer_over_key && pointer_down);
|
||||
self.playback_notes.contains(¬e) ||
|
||||
(started_here && pointer_over_key && pointer_down);
|
||||
let color = if is_pressed {
|
||||
shared.theme.bg_color(&[".piano-black-key", ".pressed"], ui.ctx(), egui::Color32::from_rgb(50, 100, 200))
|
||||
} else {
|
||||
@@ -397,7 +417,7 @@ impl VirtualPianoPane {
|
||||
ui.painter().rect_filled(key_rect, 2.0, color);
|
||||
|
||||
// Mouse down starts note
|
||||
if pointer_over_key && ui.input(|i| i.pointer.primary_pressed()) {
|
||||
if started_here && pointer_over_key && ui.input(|i| i.pointer.primary_pressed()) {
|
||||
// Calculate velocity based on mouse Y position
|
||||
let mouse_y = ui.input(|i| i.pointer.hover_pos()).unwrap().y;
|
||||
let velocity = self.calculate_velocity_from_mouse_y(mouse_y, key_rect);
|
||||
@@ -415,7 +435,7 @@ impl VirtualPianoPane {
|
||||
}
|
||||
|
||||
// Dragging over a new key
|
||||
if pointer_over_key && pointer_down {
|
||||
if started_here && pointer_over_key && pointer_down {
|
||||
if self.dragging_note != Some(note) {
|
||||
if let Some(prev_note) = self.dragging_note {
|
||||
self.send_note_off(prev_note, shared);
|
||||
@@ -824,6 +844,11 @@ impl PaneRenderer for VirtualPianoPane {
|
||||
_path: &NodePath,
|
||||
shared: &mut SharedPaneState,
|
||||
) {
|
||||
// On mobile, the octave is shared with the Piano Roll so they stay aligned.
|
||||
if shared.is_mobile {
|
||||
self.octave_offset = *shared.keyboard_octave;
|
||||
}
|
||||
|
||||
// Check if there's an active MIDI layer
|
||||
let has_active_midi_layer = if let Some(active_layer_id) = *shared.active_layer_id {
|
||||
shared.layer_to_track_map.contains_key(&active_layer_id)
|
||||
@@ -869,14 +894,28 @@ impl PaneRenderer for VirtualPianoPane {
|
||||
}
|
||||
|
||||
// Calculate visible range (needed for both rendering and labels)
|
||||
let (visible_start, visible_end, white_key_width, offset_x) =
|
||||
self.calculate_visible_range(rect.width(), rect.height());
|
||||
let (visible_start, visible_end, white_key_width, offset_x) = if shared.is_mobile {
|
||||
let layout = super::keyboard_layout::KeyboardLayout::from_width(
|
||||
rect.min.x, rect.width(), self.octave_offset, *shared.keyboard_pan_x,
|
||||
);
|
||||
let vs = layout.first_visible_white();
|
||||
(vs, layout.last_visible_note(), layout.white_key_width, layout.note_x(vs) - rect.min.x)
|
||||
} else {
|
||||
self.calculate_visible_range(rect.width(), rect.height())
|
||||
};
|
||||
|
||||
// Render the keyboard
|
||||
self.render_keyboard(ui, rect, shared);
|
||||
|
||||
// Render keyboard labels on top
|
||||
self.render_key_labels(ui, rect, shared, visible_start, visible_end, white_key_width, offset_x);
|
||||
// Render keyboard labels on top — but not on mobile (no physical keyboard to hint at).
|
||||
if !shared.is_mobile {
|
||||
self.render_key_labels(ui, rect, shared, visible_start, visible_end, white_key_width, offset_x);
|
||||
}
|
||||
|
||||
// Publish the octave so the portrait Piano Roll aligns to these keys.
|
||||
if shared.is_mobile {
|
||||
*shared.keyboard_octave = self.octave_offset;
|
||||
}
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user