beffroi-tools/crates/midra-layout/src/device_send.rs

636 lines
23 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Reviewed, explicit WebRCS layer writes. No routing, TAKE or shared input writes.
use crate::{
Layout,
device::{self, Snapshot},
};
use serde_json::{Value, json};
use std::{
collections::BTreeSet,
net::{IpAddr, SocketAddr, TcpStream},
time::Duration,
};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Target {
#[default]
Preview,
Program,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Sizing {
#[default]
OutputBox,
SourceAspect,
}
#[derive(Clone, Debug)]
pub struct Change {
pub path: Vec<String>,
pub before: Value,
pub after: Value,
}
#[derive(Clone, Debug)]
pub struct Plan {
pub screen: String,
pub bank: String,
pub target: Target,
pub changes: Vec<Change>,
}
fn field<'a>(raw: &'a Value, path: &str) -> Result<&'a Value, String> {
raw.pointer(path)
.ok_or_else(|| format!("Missing device field {path}. Refresh the connection."))
}
fn integer(v: f64, min: f64, max: f64, name: &str) -> Result<i64, String> {
let v = v.round();
if !v.is_finite() || v < min || v > max {
return Err(format!("{name} is outside the device range {min}–{max}."));
}
Ok(v as i64)
}
impl Plan {
/// Map stable editor IDs to device live-layer IDs, in one reviewed screen/bank.
pub fn prepare(
snapshot: &Snapshot,
layout: &Layout,
screen_index: usize,
mappings: &[(usize, String)],
target: Target,
sizing: Sizing,
) -> Result<Self, String> {
let screen = snapshot
.screens
.get(screen_index)
.ok_or("Choose a device screen.")?;
if mappings.is_empty() {
return Err("Choose editor layers and their Midra destinations.".into());
}
if screen.resolution != layout.formats().output {
return Err("Match the editor and device screen resolutions before sending.".into());
}
let bank = match target {
Target::Preview => screen.preview_bank.as_str(),
Target::Program => {
if screen.preview_bank == "UP" {
"DOWN"
} else {
"UP"
}
}
};
let base = format!("/device/screenList/items/{}", screen.id);
let mut plan = Self {
screen: screen.id.clone(),
bank: bank.into(),
target,
changes: vec![],
};
let mut locals = BTreeSet::new();
let mut destinations = BTreeSet::new();
for (id, destination) in mappings {
if !locals.insert(*id) || !destinations.insert(destination.clone()) {
return Err("Map each editor layer to a different Midra layer.".into());
}
if !screen.layers.iter().any(|l| l.id == *destination) {
return Err("Choose a Midra destination for every editor layer.".into());
}
let i = (0..layout.layers().len())
.find(|&i| layout.layer_info(i).id == *id)
.ok_or("An editor layer was removed.")?;
let g = layout.layers()[i].validate()?;
let source = &layout.formats().sources[layout.formats().source_for[i]];
source.input()?;
layout.formats().mapping(i, g)?;
let advanced = layout.formats().advanced[i];
let input = source.input_crop;
let crop = [
input.left + advanced.left,
input.right + advanced.right,
input.top + advanced.top,
input.bottom + advanced.bottom,
];
let native = source.native.map(f64::from);
let layer = format!("{base}/presetList/items/{bank}/liveLayerList/items/{destination}");
let content = [
field(&snapshot.raw, &format!("{layer}/status/pp/contentWidth"))?.as_f64(),
field(&snapshot.raw, &format!("{layer}/status/pp/contentHeight"))?.as_f64(),
];
if content != [Some(native[0]), Some(native[1])] {
return Err(format!(
"Layer {destination}: editor native source {} × {} differs from device content {} × {}. Match source resolution before sending.",
native[0],
native[1],
content[0].unwrap_or(0.0),
content[1].unwrap_or(0.0)
));
}
for edge in ["left", "right", "top", "bottom"] {
if field(&snapshot.raw, &format!("{layer}/mask/pp/{edge}"))?.as_i64() != Some(0) {
return Err(format!(
"Layer {destination} has a mask. Clear it in WebRCS before sending this crop-based layout."
));
}
}
let quantized: Vec<_> = crop
.iter()
.enumerate()
.map(|(j, v)| integer(v / native[j / 2] * 65535.0, 0.0, 65535.0, "Crop"))
.collect::<Result<_, _>>()?;
if quantized[0] + quantized[1] >= 65535 || quantized[2] + quantized[3] >= 65535 {
return Err("Crop quantization removes all content.".into());
}
let size = match sizing {
Sizing::OutputBox => [g.width, g.height],
Sizing::SourceAspect => {
let scale = (g.width / native[0]).max(g.height / native[1]);
[native[0] * scale, native[1] * scale]
}
};
let size = [
integer(size[0], 1.0, 65535.0, "Width")?,
integer(size[1], 1.0, 65535.0, "Height")?,
];
let retained = [
native[0] * (1.0 - (quantized[0] + quantized[1]) as f64 / 65535.0),
native[1] * (1.0 - (quantized[2] + quantized[3]) as f64 / 65535.0),
];
let scale = (size[0] as f64 / retained[0]).min(size[1] as f64 / retained[1]);
if (retained[0] * scale - g.width).abs() > 1.0
|| (retained[1] * scale - g.height).abs() > 1.0
{
return Err("Rounded device crop/size differs from the requested visible box by more than one pixel. Adjust the box or zoom.".into());
}
let center = g.center();
let mut requested = vec![
("size/pp/sizeH", json!(size[0])),
("size/pp/sizeV", json!(size[1])),
(
"position/pp/posH",
json!(integer(center[0], -67268.0, 67268.0, "Center X")?),
),
(
"position/pp/posV",
json!(integer(center[1], -67268.0, 67268.0, "Center Y")?),
),
];
for (j, path) in [
"crop/pp/left",
"crop/pp/right",
"crop/pp/top",
"crop/pp/bottom",
]
.iter()
.enumerate()
{
requested.push((path, json!(quantized[j])));
}
requested.push(("crop/pp/aspectOverride", json!("CENTERED")));
for (suffix, after) in requested {
let path = format!("{layer}/{suffix}");
let before = field(&snapshot.raw, &path)?.clone();
if before != after {
plan.changes.push(Change {
path: path
.trim_start_matches('/')
.split('/')
.map(str::to_owned)
.collect(),
before,
after,
});
}
}
}
// Release crop first so moving a heavily cropped region never temporarily
// exhausts an axis while its opposite edge still has the old value.
plan.changes.sort_by_key(|change| {
!(change.path.get(10).is_some_and(|field| field == "crop")
&& change
.after
.as_i64()
.zip(change.before.as_i64())
.is_some_and(|(after, before)| after < before))
});
Ok(plan)
}
fn verified(&self, snapshot: &Snapshot) -> bool {
self.changes
.iter()
.all(|c| snapshot.raw.pointer(&format!("/{}", c.path.join("/"))) == Some(&c.after))
}
}
trait Transport {
fn read(&mut self) -> Result<Snapshot, String>;
fn write(&mut self, change: &Change) -> Result<(), String>;
fn pause(&self) {}
}
fn execute(plan: &Plan, transport: &mut impl Transport) -> Result<Snapshot, String> {
for (i, change) in plan.changes.iter().enumerate() {
transport.write(change).map_err(|e| format!("Send stopped after {i}/{} confirmed socket writes. Device may be partially changed; refresh before retrying. {e}", plan.changes.len()))?;
}
// WebRCS commits staged preset edits with a false -> true edge.
// Always pulse, even if values already match the server's staging store.
for value in [false, true] {
let apply = Change {
path: ["device", "preset", "control", "pp", "xUpdate"]
.map(str::to_owned)
.to_vec(),
before: json!(!value),
after: json!(value),
};
transport
.write(&apply)
.map_err(|e| format!("Layer values sent, but applying preset updates failed: {e}"))?;
}
for _ in 0..10 {
transport.pause();
let snapshot = transport.read().map_err(|e| format!("Commands sent, but readback failed; outcome uncertain. Refresh before retrying. {e}"))?;
if plan.verified(&snapshot) {
return Ok(snapshot);
}
}
Err("Commands sent but readback did not match. Device may have clamped values or another controller changed them. Refresh and review; no automatic resend or rollback was performed.".into())
}
struct Connection {
host: String,
socket: Option<tungstenite::WebSocket<TcpStream>>,
}
impl Transport for Connection {
fn read(&mut self) -> Result<Snapshot, String> {
device::fetch(&self.host)
}
fn write(&mut self, change: &Change) -> Result<(), String> {
if self.socket.is_none() {
let ip: IpAddr = self.host.parse().map_err(|_| "Invalid device IP")?;
let address = SocketAddr::new(ip, 80);
let stream = TcpStream::connect_timeout(&address, Duration::from_secs(5))
.map_err(|e| e.to_string())?;
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.map_err(|e| e.to_string())?;
stream
.set_write_timeout(Some(Duration::from_secs(5)))
.map_err(|e| e.to_string())?;
let (socket, _) = tungstenite::client(format!("ws://{address}/"), stream)
.map_err(|e| e.to_string())?;
self.socket = Some(socket);
}
let message = json!({"channel":"DEVICE", "data":{"path":change.path,"value":change.after}})
.to_string();
self.socket
.as_mut()
.unwrap()
.send(tungstenite::Message::Text(message.into()))
.map_err(|e| e.to_string())
}
fn pause(&self) {
std::thread::sleep(Duration::from_millis(200));
}
}
/// Explicit send: write fields, pulse preset xUpdate, then verify geometry readback.
/// Banks are pinned; another controller's TAKE can change their on-air role.
pub fn send(host: &str, plan: &Plan) -> Result<Snapshot, String> {
let mut connection = Connection {
host: host.trim().into(),
socket: None,
};
execute(plan, &mut connection)
}
#[cfg(test)]
mod tests {
use super::*;
fn snapshot() -> Snapshot {
let layer = json!({"position":{"pp":{"posH":500,"posV":300}},"size":{"pp":{"sizeH":640,"sizeV":360}},"source":{"pp":{"input":"INPUT_4"}},"status":{"pp":{"contentWidth":1920,"contentHeight":1080}},"crop":{"pp":{"left":0,"right":0,"top":0,"bottom":0,"aspectOverride":"GLOBAL_SETTING"}},"mask":{"pp":{"left":0,"right":0,"top":0,"bottom":0}}});
let raw = json!({"device": {"preset":{"control":{"pp":{"xUpdate":true,"enableAutoUpdate":false}}},"transition":{"screenList":{"items":{"1":{"status":{"pp":{"transition":"AT_DOWN"}}}}}},"screenList":{"items":{"1":{"canvas":{"status":{"size":{"pp":{"sizeH":1920,"sizeV":1080}}}},"presetList":{"items":{"UP":{"liveLayerList":{"items":{"1":layer,"2":layer}}},"DOWN":{"liveLayerList":{"items":{"1":layer,"2":layer}}}}}}}}}});
Snapshot::parse(
&json!({"type":"Eikos 4K","version":{"major":3,"minor":3,"patch":10}}),
&raw,
)
.unwrap()
}
fn layout() -> Layout {
let mut l = Layout::default();
l.select(Some(0));
l.apply(
0,
crate::Geometry {
x: 12.0,
y: 34.0,
width: 300.0,
height: 250.0,
},
)
.unwrap();
l.set_framing(
0,
crate::formats::Framing {
zoom: 2.0,
offset: [30.0, 0.0],
},
)
.unwrap();
l
}
#[test]
fn both_strategies_include_crop_aspect_size_and_center_only() {
let s = snapshot();
let l = layout();
for (strategy, expected_width) in [(Sizing::OutputBox, 300), (Sizing::SourceAspect, 444)] {
let plan =
Plan::prepare(&s, &l, 0, &[(2, "1".into())], Target::Preview, strategy).unwrap();
assert_eq!(plan.bank, "UP");
assert!(
plan.changes
.iter()
.any(|c| c.path.last().unwrap() == "sizeH" && c.after == json!(expected_width))
);
assert!(
plan.changes
.iter()
.any(|c| c.path.last().unwrap() == "posH" && c.after == json!(162))
);
for c in plan.changes {
assert!(matches!(c.path[10].as_str(), "size" | "position" | "crop"));
assert_eq!(c.path[5], "items");
}
}
let program = Plan::prepare(
&s,
&l,
0,
&[(2, "1".into())],
Target::Program,
Sizing::OutputBox,
)
.unwrap();
assert_eq!(program.bank, "DOWN");
assert!(
Plan::prepare(
&s,
&l,
0,
&[(1, "1".into()), (2, "1".into())],
Target::Preview,
Sizing::OutputBox
)
.is_err()
);
}
struct Mock {
state: Snapshot,
writes: usize,
fail_at: Option<usize>,
ignore: bool,
writes_log: Vec<(Vec<String>, Value)>,
}
impl Transport for Mock {
fn read(&mut self) -> Result<Snapshot, String> {
Ok(self.state.clone())
}
fn write(&mut self, c: &Change) -> Result<(), String> {
if self.fail_at == Some(self.writes) {
return Err("Connection lost".into());
}
self.writes += 1;
self.writes_log.push((c.path.clone(), c.after.clone()));
if !self.ignore {
*self
.state
.raw
.pointer_mut(&format!("/{}", c.path.join("/")))
.unwrap() = c.after.clone();
}
Ok(())
}
}
#[test]
fn crop_decreases_precede_increases_when_reframing() {
let mut state = snapshot();
*state.raw.pointer_mut("/device/screenList/items/1/presetList/items/UP/liveLayerList/items/1/crop/pp/right").unwrap()=json!(50000);
let plan = Plan::prepare(
&state,
&layout(),
0,
&[(2, "1".into())],
Target::Preview,
Sizing::OutputBox,
)
.unwrap();
let right = plan
.changes
.iter()
.position(|c| c.path.last().unwrap() == "right")
.unwrap();
let left = plan
.changes
.iter()
.position(|c| c.path.last().unwrap() == "left")
.unwrap();
assert!(right < left);
}
#[test]
fn custom_input_combines_crop_once_and_rejects_mask_and_source_mismatch() {
let mut state = snapshot();
let mut l = layout();
let mut source = l.formats().sources[0];
source.input_crop.top = 40.0;
source.input_crop.bottom = 40.0;
l.configure(0, 0, source, l.layers()[0], true).unwrap();
l.set_framing(
0,
crate::formats::Framing {
zoom: 2.0,
offset: [30.0, 0.0],
},
)
.unwrap();
let plan = Plan::prepare(
&state,
&l,
0,
&[(2, "1".into())],
Target::Preview,
Sizing::OutputBox,
)
.unwrap();
let crop = l.formats().advanced[0];
let top = plan
.changes
.iter()
.find(|c| c.path.last().unwrap() == "top")
.unwrap();
assert_eq!(
top.after,
json!(((40.0 + crop.top) / 1080.0 * 65535.0).round() as i64)
);
let path = "/device/screenList/items/1/presetList/items/UP/liveLayerList/items/1";
*state
.raw
.pointer_mut(&format!("{path}/mask/pp/top"))
.unwrap() = json!(1);
assert!(
Plan::prepare(
&state,
&l,
0,
&[(2, "1".into())],
Target::Preview,
Sizing::OutputBox
)
.unwrap_err()
.contains("mask")
);
*state
.raw
.pointer_mut(&format!("{path}/mask/pp/top"))
.unwrap() = json!(0);
*state
.raw
.pointer_mut(&format!("{path}/status/pp/contentWidth"))
.unwrap() = json!(1280);
assert!(
Plan::prepare(
&state,
&l,
0,
&[(2, "1".into())],
Target::Preview,
Sizing::OutputBox
)
.unwrap_err()
.contains("differs")
);
}
#[test]
fn sent_centered_crop_imports_visible_box_and_framing_in_both_modes() {
for sizing in [Sizing::OutputBox, Sizing::SourceAspect] {
let state = snapshot();
let l = layout();
let plan =
Plan::prepare(&state, &l, 0, &[(2, "1".into())], Target::Preview, sizing).unwrap();
let mut mock = Mock {
state,
writes: 0,
fail_at: None,
ignore: false,
writes_log: vec![],
};
let result = execute(&plan, &mut mock).unwrap();
let imported = Snapshot::parse(
&json!({"type":"Eikos 4K","version":{"major":3,"minor":3,"patch":10}}),
&result.raw,
)
.unwrap();
let layer = &imported.screens[0].layers[0];
assert!(layer.unsupported.is_none());
assert!((layer.geometry.width - 300.0).abs() < 1.0);
assert!((layer.geometry.height - 250.0).abs() < 1.0);
let mut restored = Layout::default();
let before = restored.layers().clone();
let formats = restored.formats().clone();
restored
.import_device_layers(&[(Some(2), layer.geometry, layer.framing)])
.unwrap();
let framing = restored
.formats()
.mapping(0, restored.layers()[0])
.unwrap()
.framing;
assert!((framing.zoom - 2.0).abs() < 0.001);
assert!((framing.offset[0] - 30.0).abs() < 0.01);
restored.undo();
assert_eq!(*restored.layers(), before);
assert_eq!(*restored.formats(), formats);
}
}
#[test]
fn changed_device_state_does_not_block_send_and_partial_failure_is_reported() {
let state = snapshot();
let plan = Plan::prepare(
&state,
&layout(),
0,
&[(2, "1".into())],
Target::Preview,
Sizing::OutputBox,
)
.unwrap();
let mut mock = Mock {
state: state.clone(),
writes: 0,
fail_at: None,
ignore: false,
writes_log: vec![],
};
*mock
.state
.raw
.pointer_mut("/device/screenList/items/1/canvas/status/size/pp")
.unwrap() = json!(null);
assert!(plan.verified(&execute(&plan, &mut mock).unwrap()));
assert_eq!(mock.writes, plan.changes.len() + 2);
mock.state = state;
mock.writes = 0;
mock.fail_at = Some(2);
assert!(
execute(&plan, &mut mock)
.unwrap_err()
.contains("partially changed")
);
assert_eq!(mock.writes, 2);
mock.writes = 0;
mock.fail_at = Some(plan.changes.len());
assert!(
execute(&plan, &mut mock)
.unwrap_err()
.contains("applying preset updates failed")
);
}
#[test]
fn success_requires_readback_and_unchanged_values_still_apply() {
let state = snapshot();
let mut plan = Plan::prepare(
&state,
&layout(),
0,
&[(2, "1".into())],
Target::Preview,
Sizing::OutputBox,
)
.unwrap();
let mut mock = Mock {
state: state.clone(),
writes: 0,
fail_at: None,
ignore: false,
writes_log: vec![],
};
assert!(plan.verified(&execute(&plan, &mut mock).unwrap()));
assert_eq!(mock.writes, plan.changes.len() + 2);
let pulse = ["device", "preset", "control", "pp", "xUpdate"]
.map(str::to_owned)
.to_vec();
assert_eq!(
&mock.writes_log[plan.changes.len()..],
&[(pulse.clone(), json!(false)), (pulse, json!(true))]
);
assert!(
mock.writes_log[..plan.changes.len()]
.iter()
.all(|(path, _)| path.last().unwrap() != "xUpdate")
);
mock.state = state;
mock.writes = 0;
mock.ignore = true;
assert!(
execute(&plan, &mut mock)
.unwrap_err()
.contains("did not match")
);
assert_eq!(mock.writes, plan.changes.len() + 2);
plan.changes.clear();
mock.writes = 0;
execute(&plan, &mut mock).unwrap();
assert_eq!(mock.writes, 2);
}
}