Files
photoreport/workers/render/src/main.rs
spark c16730f540
ci / rust (push) Successful in 7m54s
ci / typescript (push) Successful in 11m21s
Autopilot: level by boards, not pitch lines; crops frame the upper body
The level ignores lines on grass (pitch markings tilted by perspective) and only trusts near-level or near-plumb lines that agree; otherwise the photo is left as it is. The automatic crop puts the chest a little above the middle and the spare height above the subject, instead of the knees in the middle and a strip of pitch below.

Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-13 16:45:21 +01:00

201 lines
7.9 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}
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).
let angle = source.auto_level_scene();
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
}
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))?;
// Decode at full size: the crop is taken from the original, then the result is fitted.
let source = Source::decode(&bytes, 0).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))
}
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("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();
}
}