Address code-review findings across export, decode, and data model
Export correctness: - Honor the user's color-range (Limited/Full) on the software encode path: thread full_range through gpu_yuv (new shader range uniform), the CPU swscale fallback (sws_setColorspaceDetails → BT.709 + range, fixing the BT.601 hue/level shift on odd-width exports), and the encoder color tags. - Reject HDR + WebM up front with a clear message and log the forced HEVC override instead of producing an unplayable file. - Delete dead render_frame_to_rgba_hdr (hardcoded Stretch; live HDR path already honors the fit mode). Decode/playback (video.rs): - Drain the decoder at EOF (send_eof + flush) so the final B-frame-delayed frames render instead of erroring; per-frame logic extracted to a helper. - Missing-PTS frames continue monotonically rather than snapping to ts=0. - Force exact thumbnail width so sub-128px sources aren't shown stretched. Resource leaks (gpu-video-encoder): - dmabuf import_raw: RAII guard frees the duped fd + partial VkImages/memory on every error path. - vaapi alloc: free device/frames-ctx/AVFrames on the unexpected-DRM path. Data model / robustness: - collapse_boundary_spikes requires a full curve reversal (all control points) so it no longer deletes a real lens/sliver and drops the fill. - Export audio spin-wait ignores a stale `finished` flag when a forward seek is pending (was rendering silence over real audio). - RasterDiff apply_before/after take current dims and skip on a post-resize mismatch. - beam_archive read_media_full caps the preallocation from untrusted total_len. UI/visual: - SVG export skips hidden layers/empty groups; import folds fill-opacity into gradients and surfaces failures as a notification. - Active raster-layer border uses playback_time + overlay_transform. - gpu_brush remove_layer_texture also evicts the stale low-res proxy. - ensure_raster_resident_for_undo registers faulted frames in the LRU so resident RAM stays bounded. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
1fa4d744be
commit
b301c63387
@@ -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,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];
|
||||
|
||||
@@ -57,6 +57,9 @@ pub struct VideoExportState {
|
||||
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)
|
||||
@@ -868,6 +871,7 @@ impl ExportOrchestrator {
|
||||
) -> (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);
|
||||
});
|
||||
@@ -882,6 +886,7 @@ impl ExportOrchestrator {
|
||||
height,
|
||||
hdr,
|
||||
fit,
|
||||
full_range,
|
||||
frame_tx: Some(frame_tx),
|
||||
gpu_resources: None,
|
||||
readback_pipeline: None,
|
||||
@@ -1333,8 +1338,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");
|
||||
}
|
||||
@@ -1638,6 +1643,21 @@ impl ExportOrchestrator {
|
||||
// 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 {
|
||||
@@ -1690,6 +1710,7 @@ impl ExportOrchestrator {
|
||||
framerate,
|
||||
bitrate_kbps,
|
||||
settings.hdr,
|
||||
settings.color_range.is_full(),
|
||||
)?;
|
||||
|
||||
// Pixel format the encoder frames are built in (matches setup_video_encoder).
|
||||
|
||||
@@ -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
|
||||
};
|
||||
|
||||
@@ -560,6 +560,7 @@ pub fn setup_video_encoder(
|
||||
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);
|
||||
@@ -641,7 +642,12 @@ pub fn setup_video_encoder(
|
||||
color_opts.set("profile", "main10");
|
||||
} else {
|
||||
encoder.set_colorspace(ffmpeg::color::Space::BT709);
|
||||
encoder.set_color_range(ffmpeg::color::Range::JPEG); // full range
|
||||
// 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");
|
||||
}
|
||||
@@ -1133,232 +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
|
||||
};
|
||||
|
||||
// Export composites on the encoder's own device, not the shared one, so it cannot use
|
||||
// hardware-decoded GPU frames (textures can't cross devices). Force software frames; a
|
||||
// hardware decoder downloads its surface to CPU instead.
|
||||
if let Ok(mut vm) = video_manager.lock() {
|
||||
vm.set_render_hardware_ok(false);
|
||||
}
|
||||
|
||||
// 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,
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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.
|
||||
///
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2392,6 +2392,12 @@ impl EditorApp {
|
||||
kf.needs_fault_in = false;
|
||||
}
|
||||
}
|
||||
// Track these resident pixels in the LRU so they count toward
|
||||
// RASTER_RESIDENT_MAX and can be evicted later; without this, a frame
|
||||
// faulted in for undo/redo that ends up clean would stay resident forever,
|
||||
// letting resident RAM grow past the cap.
|
||||
self.raster_resident_lru.retain(|id| *id != kf_id);
|
||||
self.raster_resident_lru.push_back(kf_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4523,7 +4529,9 @@ impl EditorApp {
|
||||
let bytes = match std::fs::read(path) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
eprintln!("❌ Failed to read SVG {}: {}", path.display(), e);
|
||||
let msg = format!("Failed to read SVG: {}", e);
|
||||
eprintln!("❌ {} ({})", msg, path.display());
|
||||
notifications::notify_error("SVG Import Failed", &msg);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -4532,6 +4540,7 @@ impl EditorApp {
|
||||
Ok(g) => g,
|
||||
Err(e) => {
|
||||
eprintln!("❌ {}", e);
|
||||
notifications::notify_error("SVG Import Failed", &e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -2080,7 +2080,11 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
|
||||
// fills the black's gaps → interlocking black/yellow marching-ants.
|
||||
if let Some(active_id) = self.ctx.active_layer_id {
|
||||
if let Some(lightningbeam_core::layer::AnyLayer::Raster(rl)) = self.ctx.document.get_layer(&active_id) {
|
||||
if let Some(kf) = rl.keyframe_at(self.ctx.document.current_time) {
|
||||
// Use playback_time (clip-local when editing a movie clip) like every other
|
||||
// keyframe lookup in prepare(), and overlay_transform so the outline tracks the
|
||||
// layer's pixels through any clip-instance affine (it equals camera_transform
|
||||
// outside clip-edit mode).
|
||||
if let Some(kf) = rl.keyframe_at(self.ctx.playback_time) {
|
||||
let rect = vello::kurbo::Rect::new(0.0, 0.0, kf.width as f64, kf.height as f64);
|
||||
// Sizes are in document space; divide by zoom so they're ~constant on screen.
|
||||
let inv_zoom = 1.0 / (self.ctx.zoom as f64).max(1e-3);
|
||||
@@ -2089,14 +2093,14 @@ impl egui_wgpu::CallbackTrait for VelloCallback {
|
||||
let pattern = [dash, dash];
|
||||
scene.stroke(
|
||||
&vello::kurbo::Stroke::new(stroke_w).with_dashes(0.0, pattern),
|
||||
camera_transform,
|
||||
overlay_transform,
|
||||
vello::peniko::Color::new([0.0, 0.0, 0.0, 1.0]),
|
||||
None,
|
||||
&rect,
|
||||
);
|
||||
scene.stroke(
|
||||
&vello::kurbo::Stroke::new(stroke_w).with_dashes(dash, pattern),
|
||||
camera_transform,
|
||||
overlay_transform,
|
||||
vello::peniko::Color::new([1.0, 0.85, 0.0, 1.0]),
|
||||
None,
|
||||
&rect,
|
||||
|
||||
@@ -118,10 +118,14 @@ fn convert_path(path: &usvg::Path, graph: &mut VectorGraph) {
|
||||
slot.color = Some(ShapeColor::rgba(c.red, c.green, c.blue, opacity_u8(fill.opacity())));
|
||||
}
|
||||
usvg::Paint::LinearGradient(g) => {
|
||||
slot.gradient_fill = Some(linear_gradient(g, ts));
|
||||
let mut grad = linear_gradient(g, ts);
|
||||
apply_fill_opacity(&mut grad, fill.opacity());
|
||||
slot.gradient_fill = Some(grad);
|
||||
}
|
||||
usvg::Paint::RadialGradient(g) => {
|
||||
slot.gradient_fill = Some(radial_gradient(g, ts));
|
||||
let mut grad = radial_gradient(g, ts);
|
||||
apply_fill_opacity(&mut grad, fill.opacity());
|
||||
slot.gradient_fill = Some(grad);
|
||||
}
|
||||
usvg::Paint::Pattern(_) => {
|
||||
// Patterns aren't representable yet — neutral gray so the shape stays visible.
|
||||
@@ -217,6 +221,17 @@ fn radial_gradient(g: &usvg::RadialGradient, abs: usvg::Transform) -> ShapeGradi
|
||||
}
|
||||
}
|
||||
|
||||
/// Fold the path's `fill-opacity` into a gradient's stop alphas (SVG multiplies them).
|
||||
fn apply_fill_opacity(grad: &mut ShapeGradient, op: usvg::Opacity) {
|
||||
let f = op.get();
|
||||
if f >= 1.0 {
|
||||
return;
|
||||
}
|
||||
for s in &mut grad.stops {
|
||||
s.color.a = (s.color.a as f32 * f).round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
}
|
||||
|
||||
fn gradient_stops(base: &usvg::BaseGradient) -> Vec<GradientStop> {
|
||||
base.stops()
|
||||
.iter()
|
||||
|
||||
Reference in New Issue
Block a user