Merge remote and fix color space

This commit is contained in:
Skyler Lehmkuhl
2026-03-01 15:50:53 -05:00
13 changed files with 1422 additions and 319 deletions
@@ -32,6 +32,7 @@ pub mod region_split;
pub mod toggle_group_expansion;
pub mod group_layers;
pub mod raster_stroke;
pub mod move_layer;
pub use add_clip_instance::AddClipInstanceAction;
pub use add_effect::AddEffectAction;
@@ -62,3 +63,4 @@ pub use region_split::RegionSplitAction;
pub use toggle_group_expansion::ToggleGroupExpansionAction;
pub use group_layers::GroupLayersAction;
pub use raster_stroke::RasterStrokeAction;
pub use move_layer::MoveLayerAction;
@@ -0,0 +1,137 @@
use crate::action::Action;
use crate::document::Document;
use crate::layer::AnyLayer;
use uuid::Uuid;
/// Action that moves one or more layers to a new position, possibly changing their parent group.
/// All layers are inserted contiguously into the same target parent.
/// Handles batch moves atomically: removes all, then inserts all, so indices stay consistent.
pub struct MoveLayerAction {
/// (layer_id, old_parent_id) for each layer to move, in visual order (top to bottom)
layers: Vec<(Uuid, Option<Uuid>)>,
new_parent_id: Option<Uuid>,
/// Insertion index in the new parent's children vec AFTER all dragged layers have been removed
new_base_index: usize,
/// Stored during execute for rollback: (layer, old_parent_id, old_index_in_parent)
removed: Vec<(AnyLayer, Option<Uuid>, usize)>,
}
impl MoveLayerAction {
pub fn new(
layers: Vec<(Uuid, Option<Uuid>)>,
new_parent_id: Option<Uuid>,
new_base_index: usize,
) -> Self {
Self {
layers,
new_parent_id,
new_base_index,
removed: Vec::new(),
}
}
}
fn get_parent_children(
document: &mut Document,
parent_id: Option<Uuid>,
) -> Result<&mut Vec<AnyLayer>, String> {
match parent_id {
None => Ok(&mut document.root.children),
Some(id) => {
let layer = document
.root
.get_child_mut(&id)
.ok_or_else(|| format!("Parent group {} not found", id))?;
match layer {
AnyLayer::Group(g) => Ok(&mut g.children),
_ => Err(format!("Layer {} is not a group", id)),
}
}
}
}
impl Action for MoveLayerAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
self.removed.clear();
// Phase 1: Remove all layers from their old parents.
// Group removals by parent, then remove back-to-front within each parent.
// Collect (layer_id, old_parent_id) with their current index.
let mut removals: Vec<(Uuid, Option<Uuid>, usize)> = Vec::new();
for (layer_id, old_parent_id) in &self.layers {
let children = get_parent_children(document, *old_parent_id)?;
let idx = children.iter().position(|l| l.id() == *layer_id)
.ok_or_else(|| format!("Layer {} not found in parent", layer_id))?;
removals.push((*layer_id, *old_parent_id, idx));
}
// Sort by (parent, index) descending so we remove back-to-front
removals.sort_by(|a, b| {
a.1.cmp(&b.1).then(b.2.cmp(&a.2))
});
let mut removed_layers: Vec<(Uuid, AnyLayer, Option<Uuid>, usize)> = Vec::new();
for (layer_id, old_parent_id, idx) in &removals {
let children = get_parent_children(document, *old_parent_id)?;
let layer = children.remove(*idx);
removed_layers.push((*layer_id, layer, *old_parent_id, *idx));
}
// Phase 2: Insert all at new parent, in visual order (self.layers order).
// self.new_base_index is the index in the post-removal children vec.
let new_children = get_parent_children(document, self.new_parent_id)?;
let base = self.new_base_index.min(new_children.len());
// Insert in forward visual order, all at `base`. Each insert pushes the previous
// one to a higher children index. Since the timeline displays children in reverse,
// a higher children index = visually higher. So the first visual layer (layers[0])
// ends up at the highest children index = visually topmost. Correct.
for (layer_id, _) in self.layers.iter() {
// Find this layer in removed_layers
let pos = removed_layers.iter().position(|(id, _, _, _)| id == layer_id)
.ok_or_else(|| format!("Layer {} missing from removed set", layer_id))?;
let (_, layer, old_parent_id, old_idx) = removed_layers.remove(pos);
self.removed.push((layer.clone(), old_parent_id, old_idx));
let new_children = get_parent_children(document, self.new_parent_id)?;
let insert_at = base.min(new_children.len());
new_children.insert(insert_at, layer);
}
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if self.removed.is_empty() {
return Err("Cannot rollback: action was not executed".to_string());
}
// Phase 1: Remove all layers from new parent (back-to-front by insertion order).
for (layer_id, _) in self.layers.iter().rev() {
let new_children = get_parent_children(document, self.new_parent_id)?;
let pos = new_children.iter().position(|l| l.id() == *layer_id)
.ok_or_else(|| format!("Layer {} not found in new parent for rollback", layer_id))?;
new_children.remove(pos);
}
// Phase 2: Re-insert at old positions, sorted by (parent, index) ascending.
let mut restore: Vec<(AnyLayer, Option<Uuid>, usize)> = self.removed.drain(..).collect();
restore.sort_by(|a, b| a.1.cmp(&b.1).then(a.2.cmp(&b.2)));
for (layer, old_parent_id, old_idx) in restore {
let children = get_parent_children(document, old_parent_id)?;
let idx = old_idx.min(children.len());
children.insert(idx, layer);
}
Ok(())
}
fn description(&self) -> String {
if self.layers.len() == 1 {
"Move layer".to_string()
} else {
format!("Move {} layers", self.layers.len())
}
}
}
@@ -12,6 +12,7 @@ use uuid::Uuid;
#[derive(Clone, Debug)]
pub enum LayerProperty {
Volume(f64),
InputGain(f64),
Muted(bool),
Soloed(bool),
Locked(bool),
@@ -25,6 +26,7 @@ pub enum LayerProperty {
#[derive(Clone, Debug)]
enum OldValue {
Volume(f64),
InputGain(f64),
Muted(bool),
Soloed(bool),
Locked(bool),
@@ -85,6 +87,7 @@ impl Action for SetLayerPropertiesAction {
if self.old_values[i].is_none() {
self.old_values[i] = Some(match &self.property {
LayerProperty::Volume(_) => OldValue::Volume(layer.volume()),
LayerProperty::InputGain(_) => OldValue::InputGain(layer.layer().input_gain),
LayerProperty::Muted(_) => OldValue::Muted(layer.muted()),
LayerProperty::Soloed(_) => OldValue::Soloed(layer.soloed()),
LayerProperty::Locked(_) => OldValue::Locked(layer.locked()),
@@ -104,6 +107,7 @@ impl Action for SetLayerPropertiesAction {
// Set new value
match &self.property {
LayerProperty::Volume(v) => layer.set_volume(*v),
LayerProperty::InputGain(g) => layer.layer_mut().input_gain = *g,
LayerProperty::Muted(m) => layer.set_muted(*m),
LayerProperty::Soloed(s) => layer.set_soloed(*s),
LayerProperty::Locked(l) => layer.set_locked(*l),
@@ -128,6 +132,7 @@ impl Action for SetLayerPropertiesAction {
if let Some(old_value) = &self.old_values[i] {
match old_value {
OldValue::Volume(v) => layer.set_volume(*v),
OldValue::InputGain(g) => layer.layer_mut().input_gain = *g,
OldValue::Muted(m) => layer.set_muted(*m),
OldValue::Soloed(s) => layer.set_soloed(*s),
OldValue::Locked(l) => layer.set_locked(*l),
@@ -159,6 +164,7 @@ impl Action for SetLayerPropertiesAction {
if let Some(&track_id) = backend.layer_to_track_map.get(&layer_id) {
match &self.property {
LayerProperty::Volume(v) => controller.set_track_volume(track_id, *v as f32),
LayerProperty::InputGain(g) => controller.set_input_gain(*g as f32),
LayerProperty::Muted(m) => controller.set_track_mute(track_id, *m),
LayerProperty::Soloed(s) => controller.set_track_solo(track_id, *s),
_ => {} // Locked/Opacity/Visible/CameraEnabled are UI-only
@@ -183,6 +189,7 @@ impl Action for SetLayerPropertiesAction {
if let Some(old_value) = &self.old_values[i] {
match old_value {
OldValue::Volume(v) => controller.set_track_volume(track_id, *v as f32),
OldValue::InputGain(g) => controller.set_input_gain(*g as f32),
OldValue::Muted(m) => controller.set_track_mute(track_id, *m),
OldValue::Soloed(s) => controller.set_track_solo(track_id, *s),
_ => {} // Locked/Opacity/Visible are UI-only
@@ -196,6 +203,7 @@ impl Action for SetLayerPropertiesAction {
fn description(&self) -> String {
let property_name = match &self.property {
LayerProperty::Volume(_) => "volume",
LayerProperty::InputGain(_) => "input gain",
LayerProperty::Muted(_) => "mute",
LayerProperty::Soloed(_) => "solo",
LayerProperty::Locked(_) => "lock",
@@ -63,6 +63,8 @@ pub trait LayerTrait {
fn set_locked(&mut self, locked: bool);
}
fn default_input_gain() -> f64 { 1.0 }
/// Base layer structure
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Layer {
@@ -87,6 +89,10 @@ pub struct Layer {
/// Audio volume (1.0 = 100%, affects nested audio layers/clips)
pub volume: f64,
/// Input gain for recording (1.0 = unity, range 0.0–4.0)
#[serde(default = "default_input_gain")]
pub input_gain: f64,
/// Audio mute state
pub muted: bool,
@@ -111,6 +117,7 @@ impl Layer {
visible: true,
opacity: 1.0,
volume: 1.0, // 100% volume
input_gain: 1.0,
muted: false,
soloed: false,
locked: false,
@@ -128,6 +135,7 @@ impl Layer {
visible: true,
opacity: 1.0,
volume: 1.0,
input_gain: 1.0,
muted: false,
soloed: false,
locked: false,
@@ -359,12 +359,19 @@ fn capture_thread_main(
let mut decoded_frame = ffmpeg::frame::Video::empty();
let mut rgba_frame = ffmpeg::frame::Video::empty();
// Helper closure: decode current packet, scale, send preview frame, and
// optionally encode into the active recorder. Returns updated frame_count.
let row_bytes = (width * 4) as usize;
let mut stop_result_tx: Option<std::sync::mpsc::Sender<Result<RecordingResult, String>>> = None;
'outer: for (stream_ref, packet) in input.packets() {
if stream_ref.index() != stream_index {
continue;
}
// Check for commands (non-blocking).
// Check for commands BEFORE decoding so that StartRecording takes effect
// on the current packet (no lost frame at the start).
while let Ok(cmd) = cmd_rx.try_recv() {
match cmd {
CaptureCommand::StartRecording {
@@ -384,20 +391,19 @@ fn capture_thread_main(
}
}
CaptureCommand::StopRecording { result_tx } => {
if let Some(rec) = recorder.take() {
let _ = result_tx.send(rec.finish());
} else {
let _ = result_tx.send(Err("Not recording".into()));
}
eprintln!("[WEBCAM stop] StopRecording command received on capture thread");
// Defer stop until AFTER we decode this packet, so the
// current frame is captured before we finalize.
stop_result_tx = Some(result_tx);
}
CaptureCommand::Shutdown => break 'outer,
}
}
// Decode current packet and process frames.
decoder.send_packet(&packet).ok();
while decoder.receive_frame(&mut decoded_frame).is_ok() {
// Skip initial corrupt frames from v4l2
if frame_count < SKIP_INITIAL_FRAMES {
frame_count += 1;
continue;
@@ -407,10 +413,8 @@ fn capture_thread_main(
let timestamp = start_time.elapsed().as_secs_f64();
// Build tightly-packed RGBA data (remove stride padding).
let data = rgba_frame.data(0);
let stride = rgba_frame.stride(0);
let row_bytes = (width * 4) as usize;
let rgba_data = if stride == row_bytes {
data[..row_bytes * height as usize].to_vec()
@@ -433,13 +437,52 @@ fn capture_thread_main(
let _ = frame_tx.try_send(frame);
if let Some(ref mut rec) = recorder {
if let Err(e) = rec.encode_rgba(&rgba_arc, width, height, frame_count) {
if let Err(e) = rec.encode_rgba(&rgba_arc, width, height, timestamp) {
eprintln!("[webcam] recording encode error: {e}");
}
}
frame_count += 1;
}
// Now handle deferred StopRecording (after the current packet is decoded).
if let Some(result_tx) = stop_result_tx.take() {
if let Some(mut rec) = recorder.take() {
// Flush any frames still buffered in the decoder.
let pre_drain_count = frame_count;
decoder.send_eof().ok();
while decoder.receive_frame(&mut decoded_frame).is_ok() {
if frame_count < SKIP_INITIAL_FRAMES {
frame_count += 1;
continue;
}
scaler.run(&decoded_frame, &mut rgba_frame).ok();
let timestamp = start_time.elapsed().as_secs_f64();
let data = rgba_frame.data(0);
let stride = rgba_frame.stride(0);
let rgba_data = if stride == row_bytes {
data[..row_bytes * height as usize].to_vec()
} else {
let mut buf = Vec::with_capacity(row_bytes * height as usize);
for y in 0..height as usize {
buf.extend_from_slice(&data[y * stride..y * stride + row_bytes]);
}
buf
};
let _ = rec.encode_rgba(&rgba_data, width, height, timestamp);
frame_count += 1;
}
eprintln!(
"[WEBCAM stop] drained {} extra frames from decoder (total frames={})",
frame_count - pre_drain_count, frame_count
);
// Reset the decoder so it can accept new packets for preview.
decoder.flush();
let _ = result_tx.send(rec.finish());
} else {
let _ = result_tx.send(Err("Not recording".into()));
}
}
}
// Clean up: if still recording when shutting down, finalize.
@@ -463,6 +506,10 @@ struct FrameRecorder {
path: PathBuf,
frame_count: u64,
fps: f64,
/// Timestamp of the first recorded frame (for offsetting PTS to start at 0)
first_timestamp: Option<f64>,
/// Timestamp of the most recent frame (for computing actual duration)
last_timestamp: f64,
}
impl FrameRecorder {
@@ -510,7 +557,10 @@ impl FrameRecorder {
encoder.set_width(aligned_width);
encoder.set_height(aligned_height);
encoder.set_format(pixel_format);
encoder.set_time_base(ffmpeg::Rational(1, fps as i32));
// Use microsecond time base for precise timestamp-based PTS.
// This avoids speedup artifacts when the camera delivers frames
// at irregular intervals (common under CPU load or with USB cameras).
encoder.set_time_base(ffmpeg::Rational(1, 1_000_000));
encoder.set_frame_rate(Some(ffmpeg::Rational(fps as i32, 1)));
if codec_id == ffmpeg::codec::Id::H264 {
@@ -549,6 +599,8 @@ impl FrameRecorder {
path: path.clone(),
frame_count: 0,
fps,
first_timestamp: None,
last_timestamp: 0.0,
})
}
@@ -557,7 +609,7 @@ impl FrameRecorder {
rgba_data: &[u8],
width: u32,
height: u32,
_global_frame: u64,
timestamp: f64,
) -> Result<(), String> {
let mut src_frame =
ffmpeg::frame::Video::new(ffmpeg::format::Pixel::RGBA, width, height);
@@ -576,8 +628,15 @@ impl FrameRecorder {
.run(&src_frame, &mut dst_frame)
.map_err(|e| format!("Scale: {e}"))?;
dst_frame.set_pts(Some(self.frame_count as i64));
// PTS in microseconds from actual capture timestamps.
// Time base is 1/1000000, so PTS = elapsed_seconds * 1000000.
// This ensures correct playback timing even when the camera delivers
// frames at irregular intervals (e.g. under CPU load).
let first_ts = *self.first_timestamp.get_or_insert(timestamp);
let elapsed_us = ((timestamp - first_ts).max(0.0) * 1_000_000.0) as i64;
dst_frame.set_pts(Some(elapsed_us));
self.frame_count += 1;
self.last_timestamp = timestamp;
self.encoder
.send_frame(&dst_frame)
@@ -616,7 +675,14 @@ impl FrameRecorder {
.write_trailer()
.map_err(|e| format!("Write trailer: {e}"))?;
let duration = self.frame_count as f64 / self.fps;
let duration = match self.first_timestamp {
Some(first_ts) => self.last_timestamp - first_ts,
None => self.frame_count as f64 / self.fps,
};
eprintln!(
"[WEBCAM finish] frames={}, first_ts={:?}, last_ts={:.4}, duration={:.4}s, fps={}",
self.frame_count, self.first_timestamp, self.last_timestamp, duration, self.fps,
);
Ok(RecordingResult {
file_path: self.path,
duration,