Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
6429654
Upstream #3054: reject XMP GPS minutes/seconds of 60 or more
emmertex Oct 27, 2026
ee89ac6
Upstream review r4: open PRs to 3119, main to c9860ea7a
emmertex Oct 27, 2026
55e696a
Upstream #3038: declare CFBundleLocalizations for macOS system dialogs
emmertex Oct 27, 2026
9025803
Upstream #3117: GPU device creation gives up after a time limit inste…
emmertex Oct 27, 2026
1794e1a
Upstream #3097: CR3 white level at the sensor's saturation point
emmertex Oct 27, 2026
cd31988
Upstream #3118: memory sizing honours cgroup limits
emmertex Oct 27, 2026
4c4913a
Merge branch 'upr/port-b' into upr/review-20261027
emmertex Oct 27, 2026
ba05360
Upstream #3045: leave Windows hidden-attribute folders out of the fol…
emmertex Oct 27, 2026
81fe7c4
Upstream #3098: CLI refused-connection tests use a free port, not 18437
emmertex Oct 27, 2026
77be5e4
Upstream #3076: --connect resends a command that crossed the idle-clo…
emmertex Oct 27, 2026
37d8f46
Merge branch 'upr/port-a' into upr/review-20261027
emmertex Oct 27, 2026
87c01dd
Merge branch 'upr/port-d' into upr/review-20261027
emmertex Oct 27, 2026
f894b0b
Upstream #3116: transparent sources keep their alpha in PNG, TIFF and…
emmertex Oct 27, 2026
54bb0ee
Upstream #3092: faces: YuNet looks at photos up to 1024 px in their o…
emmertex Oct 27, 2026
19ed5b3
Merge branch 'upr/port-c' into upr/review-20261027
emmertex Oct 27, 2026
42a0ec1
Bundle: cargo fmt after merging the ports
emmertex Oct 27, 2026
53eae7f
Merge origin/main into upr/review-20261027
emmertex Oct 27, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 41 additions & 9 deletions apps/app/src/control_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ struct TimedReader<'a> {
impl Read for TimedReader<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let (wait, why) = if self.authed.get() {
(self.idle, "control connection idle too long; closing the connection")
(self.idle, IDLE_CLOSE_ERROR)
} else {
(self.auth_by.saturating_duration_since(Instant::now()), "no `auth` request in time; closing the connection")
};
Expand Down Expand Up @@ -269,13 +269,41 @@ fn close_gracefully(stream: &TcpStream) {
}
}

/// The error of the notice sent when an idle connection is closed. Clients match the reply's
/// `"closed": "idle"` marker; `crates/mcp/src/backend.rs` also matches this text, for apps from
/// before the marker, so keep the two in step.
const IDLE_CLOSE_ERROR: &str = "control connection idle too long; closing the connection";

/// Why the server closes a connection; its error reply says so.
#[derive(Debug, PartialEq)]
enum Closing {
/// Nothing complete arrived within the idle timeout. Nothing more is read, so a request that
/// crosses the notice is never run: the reply carries `"closed": "idle"` to tell clients it is
/// safe to send that request again on a new connection.
Idle,
/// Junk, an overlong line or a failed read.
Error(String),
}

impl Closing {
fn reply(&self) -> Value {
match self {
Self::Idle => json!({"ok": false, "error": IDLE_CLOSE_ERROR, "closed": "idle"}),
Self::Error(e) => json!({"ok": false, "error": e}),
}
}
}

/// Read one `\n`-terminated line of at most `max` bytes into `buf` (newline stripped).
/// `Ok(false)` at end of stream; `Err` when the line is too long or the read fails.
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, String> {
fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -> Result<bool, Closing> {
buf.clear();
// `take` bounds the bytes buffered for one line: a peer can't make us allocate more than `max`.
let limit = u64::try_from(max).unwrap_or(u64::MAX).saturating_add(1);
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| e.to_string())?;
let n = reader.take(limit).read_until(b'\n', buf).map_err(|e| match e.kind() {
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut if e.to_string() == IDLE_CLOSE_ERROR => Closing::Idle,
_ => Closing::Error(e.to_string()),
})?;
if n == 0 {
return Ok(false);
}
Expand All @@ -287,7 +315,7 @@ fn read_bounded_line(reader: &mut impl BufRead, buf: &mut Vec<u8>, max: usize) -
return Ok(true);
}
if buf.len() > max {
return Err(format!("request line longer than {max} bytes; closing the connection"));
return Err(Closing::Error(format!("request line longer than {max} bytes; closing the connection")));
}
// Last line without a newline, then end of stream.
Ok(true)
Expand All @@ -309,12 +337,12 @@ fn serve_lines<R: Read, W: Write>(
let mut buf = Vec::new();
let mut authenticated = false;
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
let closing = match read_bounded_line(&mut reader, &mut buf, MAX_LINE) {
Ok(false) => return,
Err(e) => e,
Err(closing) => closing,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
Line::Reject(e) => e,
Line::Reject(e) => Closing::Error(e),
Line::Request { id, method, params } if !authenticated => {
let (mut r, mut ok) = control_auth::check_auth_request(&method, &params, token);
if ok && !admit() {
Expand Down Expand Up @@ -342,7 +370,7 @@ fn serve_lines<R: Read, W: Write>(
}
},
};
let _ = writeln!(out, "{}", json!({"ok": false, "error": reject})).and_then(|()| out.flush());
let _ = writeln!(out, "{}", closing.reply()).and_then(|()| out.flush());
return;
}
}
Expand Down Expand Up @@ -480,7 +508,10 @@ mod tests {
writeln!(c, "{}", control_auth::auth_request(json!(1), TOKEN)).unwrap();
let mut text = String::new();
c.read_to_string(&mut text).unwrap();
assert!(text.contains("idle too long"), "{text}");
let reply: Value = serde_json::from_str(text.lines().nth(1).unwrap_or_default()).unwrap();
assert_eq!(reply["error"], IDLE_CLOSE_ERROR);
assert_eq!(reply["closed"], "idle", "clients may resend a request that crossed this notice");
assert!(reply.get("id").is_none());
let t0 = Instant::now();
while slots.authed.load(Ordering::SeqCst) != 0 && t0.elapsed() < Duration::from_secs(5) {
std::thread::sleep(Duration::from_millis(10));
Expand Down Expand Up @@ -603,6 +634,7 @@ mod tests {
assert_eq!(r.len(), 1);
assert_eq!(r[0]["ok"], false);
assert!(r[0]["error"].as_str().unwrap().contains("closing the connection"));
assert!(r[0].get("closed").is_none(), "only an idle close invites a resend: {}", r[0]);
}

#[test]
Expand Down
4 changes: 3 additions & 1 deletion apps/app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,9 @@ fn window_files(in_memory: bool) -> window_gpu::Files {
}

/// Written while the GPU compute device is created, removed once that returned
/// (`lcc_gpu::backend::set_init_marker`). Not with `<PREFIX>_NO_PREFS` (tests, scripts).
/// (`lcc_gpu::backend::set_init_marker`); still there after a quit while a creation that
/// passed its time limit was stuck in the driver (#3068). Not with `<PREFIX>_NO_PREFS` (tests,
/// scripts).
fn gpu_marker_path() -> Option<std::path::PathBuf> {
if lcc_brand::env_is_set("NO_PREFS") {
return None;
Expand Down
70 changes: 62 additions & 8 deletions apps/cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -970,6 +970,57 @@ fn snapshot_starts_without_a_gpu() {
}
}

/// A loopback port nothing listens on, for tests that need `--connect` to be refused (#3070).
/// A fixed port is not safe: agents give their apps' control servers ports in 18000–19999 (and
/// 7980 is the default), so a test could reach someone's running app and drive it. The OS hands
/// out a free port for `:0`; the listener is dropped so connecting to it is refused. Another
/// process could bind the port between the drop and the connect. That window is a few
/// milliseconds, and `:0` draws from the OS's ephemeral range (from 32768 on Linux, 49152 on
/// macOS and Windows), where nobody puts a control server (7980, 18000–19999): the standard
/// trade-off for a test that needs a refused connection.
fn unused_port() -> u16 {
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}

/// Issue #2976: a transparent PNG exported as PNG kept its pixels but lost its alpha (flattened
/// onto white); JPEG still composites onto white.
#[test]
fn transparent_png_export_keeps_its_alpha() {
let input = tmp("alpha-in.png");
// 300 × 200, transparent, with an opaque 150 × 100 rectangle in the middle
let img =
lcc_raster::Rgba8::from_fn(300, 200, |x, y| if (75..225).contains(&x) && (50..150).contains(&y) { [200, 40, 30, 255] } else { [0, 0, 0, 0] });
let png = lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(&img), &Default::default()).unwrap();
std::fs::write(&input, png).unwrap();
let (png_out, jpg_out) = (tmp("alpha-out.png"), tmp("alpha-out.jpg"));
for out in [&png_out, &jpg_out] {
let _ = std::fs::remove_file(out);
let (ok, lines, err) = run_cli(&["--import", input.to_str().unwrap(), "app.export", &format!("path={}", out.display())], None);
assert!(ok && lines.iter().all(|l| l["ok"] == true), "{err} {lines:?}");
}

let d = lcc_codecs::decode(&std::fs::read(&png_out).unwrap(), Default::default()).unwrap();
assert!(d.has_alpha, "the PNG keeps an alpha channel");
assert_eq!((d.width, d.height), (300, 200));
let px = d.to_srgb8();
for (x, y) in [(2, 2), (297, 2), (2, 197), (297, 197), (40, 100)] {
assert_eq!(px.get(x, y)[3], 0, "transparent at ({x}, {y})");
}
let centre = px.get(150, 100);
assert_eq!(centre[3], 255, "opaque in the rectangle");
assert!(centre[0].abs_diff(200) <= 2 && centre[1].abs_diff(40) <= 2 && centre[2].abs_diff(30) <= 2, "{centre:?}");
// the rectangle's edge stays where it was, without a white fringe
assert_eq!(px.get(74, 100)[3], 0);
let edge = px.get(75, 100);
assert_eq!(edge[3], 255);
assert!(edge[1] < 60, "no white fringe: {edge:?}");

let j = lcc_codecs::decode(&std::fs::read(&jpg_out).unwrap(), Default::default()).unwrap();
assert!(!j.has_alpha);
let corner = j.to_srgb8().get(2, 2);
assert!(corner.iter().take(3).all(|&c| c >= 250), "JPEG composites onto white: {corner:?}");
}

fn run_cli(args: &[&str], stdin: Option<&str>) -> (bool, Vec<Value>, String) {
let mut child = Command::new(BIN).arg("run").args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
if let Some(text) = stdin {
Expand Down Expand Up @@ -1117,9 +1168,10 @@ fn a_library_open_in_another_process_is_refused() {
/// ADDR actually names — following the old fixed "7980" left the retry connecting elsewhere.
#[test]
fn connect_failure_hint_names_the_attempted_port() {
let (ok, _lines, err) = run_cli(&["--connect", "127.0.0.1:18437", "ui.inspect"], None);
let port = unused_port();
let (ok, _lines, err) = run_cli(&["--connect", &format!("127.0.0.1:{port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "the hint must name the port it tried: {err}");
assert!(err.contains(&format!("--control {port}")), "the hint must name the port it tried: {err}");
assert!(!err.contains("--control 7980"), "{err}");
}

Expand All @@ -1129,20 +1181,22 @@ fn connect_failure_hint_names_the_attempted_port() {
/// works; non-numeric, non-`ADDR`-shaped tokens (e.g. a real command id) keep falling through.
#[test]
fn connect_bare_port_is_treated_as_loopback_port() {
let port = unused_port();
let hint = format!("--control {port}");
// Bare port: the failure hint names that port.
let (ok, _lines, err) = run_cli(&["--connect", "18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&["--connect", &port.to_string(), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "bare port must reach the hint: {err}");
assert!(err.contains(&hint), "bare port must reach the hint: {err}");
assert!(!err.contains("--control 7980"), "{err}");
// `<host>:<port>` still works (issue #167 case).
let (ok, _lines, err) = run_cli(&["--connect", "127.0.0.1:18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&["--connect", &format!("127.0.0.1:{port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "{err}");
assert!(err.contains(&hint), "{err}");
// `--connect=<bare-port>` already worked (the `a.starts_with("--connect=")` arm); spot-check
// the hint matches its port too.
let (ok, _lines, err) = run_cli(&["--connect=18437", "ui.inspect"], None);
let (ok, _lines, err) = run_cli(&[&format!("--connect={port}"), "ui.inspect"], None);
assert!(!ok);
assert!(err.contains("--control 18437"), "{err}");
assert!(err.contains(&hint), "{err}");
}

/// The CLI logs warnings on stderr (#168): with `RUST_LOG=warn` an unknown GPU backend name is
Expand Down
1 change: 1 addition & 0 deletions apps/web/src/wire.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ impl WireJob {
window: self.window.map(|[x, y, w, h]| lcc_engine::pipeline::PixelWindow { x, y, w, h }),
display: None,
downscale: lcc_engine::pipeline::Downscale::Smooth,
alpha: false,
}
}

Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/workers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ async fn handle(scope: &web_sys::DedicatedWorkerGlobalScope, backend: Option<Bac
match b.read(&key).await.ok().flatten().and_then(|bytes| lcc_preview::decode_jpeg(&bytes)) {
Some(image) => {
let histogram = Histogram::of_srgb8(&image);
return Ok((Rendered { image, histogram, deep: None, warnings: Vec::new(), coverage: None }, 0));
return Ok((Rendered { image, histogram, deep: None, warnings: Vec::new(), coverage: None, alpha: None }, 0));
}
None => cache_miss = true,
}
Expand Down Expand Up @@ -326,7 +326,7 @@ impl Workers {
let rgba = Uint8Array::new(&get(&data, "rgba")).to_vec();
let hist = Uint32Array::new(&get(&data, "hist")).to_vec();
match (Rgba8::from_bytes(wd, ht, &rgba), Histogram::from_words(&hist)) {
(Some(image), Some(histogram)) => Ok(Rendered { image, histogram, deep: None, warnings: Vec::new(), coverage: None }),
(Some(image), Some(histogram)) => Ok(Rendered { image, histogram, deep: None, warnings: Vec::new(), coverage: None, alpha: None }),
_ => Err("render worker: bad image".to_string()),
}
} else {
Expand Down Expand Up @@ -443,7 +443,7 @@ impl RenderOffload for Workers {
photo: job.photo,
level: job.level,
key: job.key,
rendered: Ok(Rendered { image, histogram, deep: None, warnings: Vec::new(), coverage: None }),
rendered: Ok(Rendered { image, histogram, deep: None, warnings: Vec::new(), coverage: None, alpha: None }),
gpu_fallback: None,
loaded: None,
quick: None,
Expand Down
6 changes: 6 additions & 0 deletions crates/camdb/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,12 @@ impl Entry {
}
if let Some(w) = self.white {
raw.white = vec![w; cpp];
// the entry's white level replaces any the decoder raised to the sensor's saturation point (CR3), and with
// it the baseline exposure that raise added
if raw.color.white_extension_ev.is_finite() {
raw.color.baseline_exposure -= raw.color.white_extension_ev;
}
raw.color.white_extension_ev = 0.0;
applied.levels = true;
}
applied
Expand Down
44 changes: 32 additions & 12 deletions crates/codecs/src/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,32 @@ impl Buf {
}
}

/// Divide associated alpha out of the colour samples of interleaved pixels of `ch` channels, the
/// last of which is alpha (integer colour is capped at full scale; zero alpha leaves the colour).
fn unpremultiply(buf: &mut Buf, ch: usize) {
fn each<T: Copy>(v: &mut [T], ch: usize, f: impl Fn(T, T) -> T) {
if ch < 2 {
return;
}
for px in v.chunks_exact_mut(ch) {
if let Some((&mut a, colour)) = px.split_last_mut() {
for c in colour {
*c = f(*c, a);
}
}
}
}
match buf {
Buf::U8(v) => each(v, ch, |c, a| if a == 0 { c } else { ((c as u32 * 255 + a as u32 / 2) / a as u32).min(255) as u8 }),
Buf::U16(v) => each(v, ch, |c, a| if a == 0 { c } else { ((c as u64 * 65535 + a as u64 / 2) / a as u64).min(65535) as u16 }),
// (non-finite samples clipped first, as the colour conversion and the alpha plane clip them)
Buf::F32(v) => each(v, ch, |c, a| {
let (c, a) = (normalize_float(c), normalize_float(a).clamp(0.0, 1.0));
if a > 0.0 { c / a } else { c }
}),
}
}

/// Clip non-finite device samples before colour conversion, preserving finite extended range.
#[inline]
fn normalize_float(value: f32) -> f32 {
Expand Down Expand Up @@ -125,12 +151,17 @@ pub(crate) fn check_size(format: Format, w: u64, h: u64, opts: &DecodeOptions) -
Ok(())
}

pub(crate) fn finish(format: Format, raw: Raw, meta: Meta, source_dims: (u32, u32), opts: &DecodeOptions) -> Result<Decoded> {
pub(crate) fn finish(format: Format, mut raw: Raw, meta: Meta, source_dims: (u32, u32), opts: &DecodeOptions) -> Result<Decoded> {
let ch = raw.model.channels() + raw.alpha as usize;
let n = crate::checked_samples(raw.width, raw.height, 1)?;
if n == 0 || raw.buf.len() < crate::checked_samples(raw.width, raw.height, ch)? {
return Err(Error::Malformed(format, "sample buffer too short".into()));
}
// Associated alpha is multiplied into the stored (encoded) colour values, as image editors and
// our TIFF export write it: divide it out before those values are decoded to linear light.
if raw.premultiplied && raw.alpha {
unpremultiply(&mut raw.buf, ch);
}
let float = matches!(raw.buf, Buf::F32(_));

// Alpha plane (straight).
Expand All @@ -153,17 +184,6 @@ pub(crate) fn finish(format: Format, raw: Raw, meta: Meta, source_dims: (u32, u3
rgb_or_gray(&raw, ch, &meta, parsed_icc.as_ref(), float)?
};

let mut image = image;
if raw.premultiplied
&& let Some(a) = &alpha
{
for (p, &av) in image.data.iter_mut().zip(&a.data) {
if av > 0.0 {
*p = p.map(|c| c / av);
}
}
}

let summary = meta.exif.as_deref().map(exif::summarize).unwrap_or_default();
let orientation = meta.orientation.or(summary.orientation).filter(|o| (1..=8).contains(o)).unwrap_or(1);

Expand Down
Loading
Loading