Files
photoreport/workers/render/src/main.rs
T
spark 635160b66e
ci / rust (pull_request) Successful in 4m25s
ci / typescript (pull_request) Successful in 7m38s
fix(autopilot): pick open eyes, clear faces; edit only picks; level fallback (BIT-170)
Shut eyes and backs no longer win a burst when an open-eyed face exists. Develop/crop
runs only on the picked frames (not the whole sequence). Bursts without EXIF group by
ingest time. Level falls back to LightCraft when stadium lines disagree.
2026-11-03 21:47:37 +00:00

281 lines
11 KiB
Rust

//! Long-running render process, driven by the API worker over stdin/stdout, one JSON object per line:
//! in: {"id": "...", "input": "/abs/original.jpg", "output": "/abs/out.jpg", "settings": {..},
//! "maxEdge": 4000, "quality": 100}
//! out: {"id": "...", "width": W, "height": H} or {"id": "...", "error": "..."}
//! `maxEdge` 0 keeps the full size. The output is sRGB without metadata; the caller copies EXIF and IPTC.
//! Automatic first pass (autopilot): white balance, tone (under that white balance) and the level angle:
//! in: {"id": "...", "auto": {"input": "/abs/preview.jpg", "settings": {..} | null}}
//! out: {"id": "...", "values": {"wb.temp": .., "light.exposure": .., ..}, "angle": -1.2 | null}
//! Settings from an op log:
//! in: {"id": "...", "base": {..settings..} | null, "commands": [{"command": "develop.set", "params": {..}}, ..]}
//! out: {"id": "...", "settings": {..}, "skipped": [indexes of commands that were refused], "unedited": bool}
//! Capture metadata (LightCraft: EXIF, then IPTC, then XMP, including CR3 and a loose XMP sidecar):
//! in: {"id": "...", "meta": {"input": "/abs/photo.cr3"}}
//! out: {"id": "...", "capture": { "cameraMake": "..", "exposureTime": 0.01, "exposureBias": -2, .. }}
use std::io::{BufRead, Write};
use photoreport_engine::render::{Source, encode_jpeg};
use photoreport_engine::{DevelopSettings, EditCommand, apply_command};
use serde::Deserialize;
#[derive(Deserialize)]
struct Replay {
id: String,
#[serde(default)]
base: serde_json::Value,
commands: Vec<serde_json::Value>,
}
/// Replays commands on top of `base`. A command this engine refuses (unknown control from a newer client,
/// malformed) is skipped and reported, never fatal: the rest of the photo's edit still applies.
fn replay(job: &Replay) -> Result<(serde_json::Value, Vec<usize>, bool), String> {
let mut settings = if job.base.is_null() {
DevelopSettings::default()
} else {
DevelopSettings::from_json(&job.base).map_err(|e| e.to_string())?
};
let mut skipped = Vec::new();
for (i, raw) in job.commands.iter().enumerate() {
match serde_json::from_value::<EditCommand>(raw.clone())
.map_err(|e| e.to_string())
.and_then(|c| apply_command(&settings, &c).map_err(|e| e.to_string()))
{
Ok(next) => settings = next,
Err(_) => skipped.push(i),
}
}
Ok((settings.to_json(), skipped, settings.is_unedited()))
}
#[derive(Deserialize)]
struct AutoRequest {
id: String,
auto: AutoJob,
}
#[derive(Deserialize)]
struct AutoJob {
input: String,
#[serde(default)]
settings: serde_json::Value,
}
/// White balance first, then tone under it (as an editor would), and the angle that levels the photo.
fn auto(job: &AutoJob) -> Result<(serde_json::Value, Option<f64>), String> {
let mut settings = if job.settings.is_null() {
DevelopSettings::default()
} else {
DevelopSettings::from_json(&job.settings).map_err(|e| e.to_string())?
};
let bytes = std::fs::read(&job.input).map_err(|e| format!("{}: {e}", job.input))?;
// A 1024 px working image is plenty for statistics and lines, and keeps this fast.
let source = Source::decode(&bytes, 1024).map_err(|e| e.to_string())?;
let mut values = serde_json::Map::new();
let wb = source.auto_wb();
let set = |settings: &DevelopSettings,
pairs: &[(&'static str, f64)]|
-> Result<DevelopSettings, String> {
let command: EditCommand = serde_json::from_value(serde_json::json!({
"command": "develop.set",
"params": { "values": pairs.iter().map(|(k, v)| ((*k).to_string(), serde_json::json!(v))).collect::<serde_json::Map<_, _>>() }
}))
.map_err(|e| e.to_string())?;
apply_command(settings, &command).map_err(|e| e.to_string())
};
settings = set(&settings, &wb)?;
let tone = source.auto_tone(&settings);
for (k, v) in wb.iter().chain(tone.iter()) {
values.insert((*k).to_string(), serde_json::json!(v));
}
// Stadium photos: the pitch markings must not decide the level (see photoreport_engine::level).
// When boards/stands/posts do not agree (tight indoor crops, empty seats), fall back to LightCraft's Level.
let angle = source
.auto_level_scene()
.or_else(|| source.auto_level(&settings));
Ok((serde_json::Value::Object(values), angle))
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Job {
id: String,
input: String,
output: String,
#[serde(default)]
settings: serde_json::Value,
#[serde(default)]
max_edge: u32,
#[serde(default = "default_quality")]
quality: u8,
}
fn default_quality() -> u8 {
100
}
/// How much of the frame the crop keeps, on its larger side. A whole frame is 1.
fn kept_fraction(settings: &DevelopSettings) -> f64 {
let rect = settings.crop.geometry.rect;
let width = (rect.x1 - rect.x0).clamp(0.0, 1.0);
let height = (rect.y1 - rect.y0).clamp(0.0, 1.0);
width.max(height).clamp(0.05, 1.0)
}
/// Longest side to decode. The crop only needs enough pixels for the output, not the whole file.
/// `max_edge == 0` stays full size. A little extra covers a straighten.
fn decode_edge(settings: &DevelopSettings, max_edge: u32) -> u32 {
if max_edge == 0 {
return 0;
}
let need = (max_edge as f64 / kept_fraction(settings)).ceil() as u32;
need.saturating_add(need / 8).max(max_edge)
}
fn run(job: &Job) -> Result<(u32, u32), String> {
let settings = if job.settings.is_null() {
DevelopSettings::default()
} else {
DevelopSettings::from_json(&job.settings).map_err(|e| e.to_string())?
};
let bytes = std::fs::read(&job.input).map_err(|e| format!("{}: {e}", job.input))?;
let source =
Source::decode(&bytes, decode_edge(&settings, job.max_edge)).map_err(|e| e.to_string())?;
drop(bytes);
let edge = if job.max_edge == 0 {
u32::MAX
} else {
job.max_edge
};
let px = source.render(&settings, edge, edge, false, true);
let jpeg = encode_jpeg(&px, job.quality).map_err(|e| e.to_string())?;
let tmp = format!("{}.part", job.output);
std::fs::write(&tmp, jpeg).map_err(|e| format!("{tmp}: {e}"))?;
std::fs::rename(&tmp, &job.output).map_err(|e| format!("{}: {e}", job.output))?;
Ok((px.width, px.height))
}
#[derive(Deserialize)]
struct MetaRequest {
id: String,
meta: MetaJob,
}
#[derive(Deserialize)]
struct MetaJob {
input: String,
}
/// Capture metadata of one file. The same JSON the browser engine returns.
fn capture_file(path: &str) -> Result<serde_json::Value, String> {
let bytes = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?;
Ok(photoreport_engine::capture::read_capture(&bytes))
}
fn main() {
let stdout = std::io::stdout();
let mut out = stdout.lock();
let _ = writeln!(out, "{}", serde_json::json!({ "ready": true }));
let _ = out.flush();
for line in std::io::stdin().lock().lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
continue;
}
let value: serde_json::Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => {
let _ = writeln!(
out,
"{}",
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
);
let _ = out.flush();
continue;
}
};
if value.get("meta").is_some() {
let reply = match serde_json::from_value::<MetaRequest>(value) {
Ok(req) => match capture_file(&req.meta.input) {
Ok(capture) => serde_json::json!({ "id": req.id, "capture": capture }),
Err(error) => serde_json::json!({ "id": req.id, "error": error }),
},
Err(e) => {
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
}
};
let _ = writeln!(out, "{reply}");
let _ = out.flush();
continue;
}
if value.get("auto").is_some() {
let reply = match serde_json::from_value::<AutoRequest>(value) {
Ok(req) => match auto(&req.auto) {
Ok((values, angle)) => {
serde_json::json!({ "id": req.id, "values": values, "angle": angle })
}
Err(error) => serde_json::json!({ "id": req.id, "error": error }),
},
Err(e) => {
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
}
};
let _ = writeln!(out, "{reply}");
let _ = out.flush();
continue;
}
if value.get("commands").is_some() {
let reply = match serde_json::from_value::<Replay>(value) {
Ok(job) => match replay(&job) {
Ok((settings, skipped, unedited)) => {
serde_json::json!({ "id": job.id, "settings": settings, "skipped": skipped, "unedited": unedited })
}
Err(error) => serde_json::json!({ "id": job.id, "error": error }),
},
Err(e) => {
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
}
};
let _ = writeln!(out, "{reply}");
let _ = out.flush();
continue;
}
let reply = match serde_json::from_value::<Job>(value) {
Ok(job) => match run(&job) {
Ok((w, h)) => serde_json::json!({ "id": job.id, "width": w, "height": h }),
Err(error) => serde_json::json!({ "id": job.id, "error": error }),
},
Err(e) => {
serde_json::json!({ "id": serde_json::Value::Null, "error": format!("bad request: {e}") })
}
};
let _ = writeln!(out, "{reply}");
let _ = out.flush();
}
}
#[cfg(test)]
mod tests {
use super::{DevelopSettings, capture_file, decode_edge};
#[test]
fn a_missing_file_is_an_error() {
let err = capture_file("/no/such/photo.cr3").unwrap_err();
assert!(err.contains("photo.cr3"), "{err}");
}
#[test]
fn a_tight_crop_decodes_enough_for_the_output() {
let mut settings = DevelopSettings::default();
settings.crop.geometry.rect.x0 = 0.2;
settings.crop.geometry.rect.x1 = 0.6;
settings.crop.geometry.rect.y0 = 0.1;
settings.crop.geometry.rect.y1 = 0.9;
// The taller side is 0.8 of the frame: 2048 / 0.8 = 2560, plus an eighth.
assert_eq!(decode_edge(&settings, 2048), 2880);
assert_eq!(decode_edge(&settings, 0), 0);
// A whole frame still decodes a little above the output, never the full file.
assert_eq!(decode_edge(&DevelopSettings::default(), 4000), 4500);
}
}