Skip to main content

printobserver_server/
check_images.rs

1//! The image every check is shown, made of the frame the camera gave.
2//!
3//! The one place that chooses it ([`PanelImages`]). A check of a print is shown
4//! `printobserver-panels`' three-panel check image when that image can be
5//! trusted: a calibration is configured, the print's G-code index names the
6//! object being laid and the layer at the check's file position, the print's
7//! first-layer alignment `Passed`, and the frame passes the composer's
8//! resolution, stream and drift checks. Every other check, and every look at
9//! the printer, is shown the whole frame scaled to [`WHOLE_FRAME_WIDTH`] by
10//! [`WHOLE_FRAME_HEIGHT`] and never cropped ([`WholeFrames`]). Either way the
11//! image is written under `<state_dir>/check-images/` while the stored frame
12//! keeps the camera's size, and one line says which image it is and why.
13
14use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use std::sync::Arc;
18
19use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
20use printobserver_panels::{
21    CameraCalibration, CheckImage, CheckImageInputs, ComposeError, WHOLE_FRAME_HEIGHT,
22    WHOLE_FRAME_WIDTH, compose_check_image, whole_frame,
23};
24use printobserver_types::{PrintId, Timestamp};
25
26use crate::alignment::{AlignmentFailure, Alignments, PreviousCheck, PrintAlignment};
27
28/// How many scaled frames this process has begun writing, which names each
29/// write's partial file apart from any other's.
30static WRITES: AtomicU64 = AtomicU64::new(0);
31
32/// The directory under the state directory check images are written in.
33pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
34
35/// Every check shown the whole frame, scaled.
36#[derive(Debug, Clone)]
37pub struct WholeFrames {
38    /// Where the scaled frames are written.
39    directory: PathBuf,
40}
41
42impl WholeFrames {
43    /// Write scaled frames under one state directory.
44    #[must_use]
45    pub fn under(state_dir: &Path) -> Self {
46        Self {
47            directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
48        }
49    }
50
51    /// Where the scaled copy of one stored frame is written: named for the
52    /// stored frame's own directory and file, which name it uniquely.
53    fn destination(&self, frame: &Path) -> PathBuf {
54        let named = |part: Option<&std::ffi::OsStr>| {
55            part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
56        };
57        let parent = named(frame.parent().and_then(Path::file_name));
58        let file = named(frame.file_name());
59        self.directory.join(format!(
60            "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
61        ))
62    }
63}
64
65impl CheckImages for WholeFrames {
66    fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
67        let destination = self.destination(frame);
68        if destination.is_file() {
69            return Ok(destination);
70        }
71        let bytes = std::fs::read(frame)
72            .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
73        let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
74        if !scaled.scaled {
75            return Ok(frame.to_path_buf());
76        }
77        write_image(&self.directory, &destination, &scaled.jpeg)?;
78        Ok(destination)
79    }
80}
81
82/// Write one check image — a scaled frame or a three-panel image — under
83/// `directory` at `destination`, beside its name first
84/// and moved onto it, so a reader never opens a half-written image.
85fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
86    std::fs::create_dir_all(directory)
87        .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
88    let partial = destination.with_extension(format!(
89        "{}-{}.partial",
90        std::process::id(),
91        WRITES.fetch_add(1, Ordering::Relaxed)
92    ));
93    let written =
94        std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
95    written.map_err(|error| {
96        // Whatever was written is no image a reader may open.
97        let _ = std::fs::remove_file(&partial);
98        format!("{} cannot be written: {error}", destination.display())
99    })
100}
101
102/// The first words of every line saying a check was shown the three-panel
103/// image, which the real-print suite's record reads the image's kind from.
104pub const COMPOSITE_NOTE: &str = "the three-panel check image";
105
106/// The first words of every line saying a check was shown the whole frame.
107pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
108
109/// Why a check is shown the whole frame rather than the three-panel image.
110#[derive(Debug, Clone, PartialEq)]
111pub enum WholeFrameReason {
112    /// No print is named: a look at the printer, before, between or after
113    /// prints, a start's bed check among them.
114    NoPrint,
115    /// No camera calibration is configured.
116    NoCalibration,
117    /// No camera snapshot address is configured, so the frame's stream is
118    /// unknown.
119    NoStream,
120    /// The job is not the print's file, reported no position, or its file has
121    /// no index.
122    NoPosition,
123    /// The print's G-code names no extruded object, or none laid yet, at the
124    /// check's file position.
125    NoObject,
126    /// It names no layer there.
127    NoLayer,
128    /// The layer's planned toolpath could not be read from the print's spool.
129    ToolpathUnread(String),
130    /// The print's first-layer alignment is not decided yet.
131    AlignmentPending,
132    /// The print's G-code lays no object to align.
133    AlignmentUnavailable,
134    /// The print's first-layer alignment failed.
135    AlignmentFailed(AlignmentFailure),
136    /// The composer refused this frame.
137    Refused(ComposeError),
138}
139
140impl core::fmt::Display for WholeFrameReason {
141    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
142        match self {
143            Self::NoPrint => formatter
144                .write_str("no print is named, so there is no planned toolpath to draw on it"),
145            Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
146            Self::NoStream => formatter.write_str(
147                "no camera snapshot address is configured, so the frame's stream is unknown",
148            ),
149            Self::NoPosition => formatter.write_str(
150                "the print's G-code index gives no file position for this check",
151            ),
152            Self::NoObject => formatter.write_str(
153                "the print's G-code names no extruded object laid at this point",
154            ),
155            Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
156            Self::ToolpathUnread(detail) => write!(
157                formatter,
158                "the layer's planned toolpath could not be read from the print's spool: {detail}"
159            ),
160            Self::AlignmentPending => formatter.write_str(
161                "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
162            ),
163            Self::AlignmentUnavailable => {
164                formatter.write_str("the print's G-code lays no object to align")
165            }
166            Self::AlignmentFailed(AlignmentFailure::Offset { offset_px }) => write!(
167                formatter,
168                "the print's first-layer alignment failed: the printed first layer lies {offset_px:.1} px from where the calibration projects it"
169            ),
170            Self::AlignmentFailed(AlignmentFailure::Resolution { expected, got }) => write!(
171                formatter,
172                "the print's first-layer alignment failed: the camera's frames are {}x{} and the calibration's {}x{}",
173                got[0], got[1], expected[0], expected[1]
174            ),
175            Self::AlignmentFailed(AlignmentFailure::Stream) => formatter.write_str(
176                "the print's first-layer alignment failed: the camera is not the stream the calibration was fitted on",
177            ),
178            Self::Refused(error) => error.fmt(formatter),
179        }
180    }
181}
182
183/// The line saying a check was shown the whole frame, and why.
184#[must_use]
185pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
186    format!(
187        "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}"
188    )
189}
190
191/// The line saying a check was shown the three-panel image: panel 3 empty
192/// when no earlier check's frame is at hand — the print's first check, or one
193/// whose earlier frame is gone from the store.
194#[must_use]
195pub fn composite_note(no_previous: bool) -> String {
196    let previous = if no_previous {
197        "panel 3 empty, no earlier check's frame being at hand"
198    } else {
199        "panel 3 the previous check's frame"
200    };
201    format!(
202        "{COMPOSITE_NOTE}, {}x{}: panel 1 this layer's planned toolpath drawn on the frame, panel 2 a close-up of the part being printed, {previous}",
203        printobserver_panels::compose::PANEL_WIDTH,
204        printobserver_panels::compose::IMAGE_HEIGHT
205    )
206}
207
208/// What a check image is composed from, beyond the frames: the print's plan at
209/// one file position.
210#[derive(Debug, Clone, Copy)]
211pub struct PlanAt<'a> {
212    /// The print's G-code index, its toolpaths read from its spool.
213    pub index: &'a GcodeIndex,
214    /// The check's file position.
215    pub file_position_bytes: u64,
216}
217
218/// Compose the three-panel check image of one frame at one file position, as
219/// every check of a print whose alignment passed is shown it: the active
220/// object at that position, the layer there — and, when that layer lays
221/// supports alone, the nearest object layer below it — over the frame, with
222/// `previous` as panel 3.
223///
224/// # Errors
225///
226/// [`WholeFrameReason`] naming what the index lacks at that position, or the
227/// composer's own refusal.
228pub fn compose_at(
229    plan: PlanAt<'_>,
230    current: (&[u8], Timestamp),
231    previous: Option<(&[u8], Timestamp)>,
232    camera_snapshot_url: &str,
233    calibration: &CameraCalibration,
234) -> Result<CheckImage, WholeFrameReason> {
235    let index = plan.index;
236    let position = plan.file_position_bytes;
237    let active_object = index
238        .object_at(position)
239        .filter(|object| *object < index.object_outlines().len())
240        .ok_or(WholeFrameReason::NoObject)?;
241    let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
242    let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
243    let unread =
244        |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
245    let toolpath = index.layer_toolpath(layer).map_err(unread)?;
246    let below = if toolpath.carries_object_extrusion() {
247        None
248    } else {
249        index
250            .object_layer_at_or_below(layer)
251            .map(|below| index.layer_toolpath(below))
252            .transpose()
253            .map_err(unread)?
254    };
255    compose_check_image(&CheckImageInputs {
256        current_jpeg: current.0,
257        current_at: current.1,
258        camera_snapshot_url,
259        previous,
260        outlines: index.object_outlines(),
261        active_object,
262        toolpath: &toolpath,
263        object_layer_below: below.as_ref(),
264        print_z_mm,
265        calibration,
266    })
267    .map_err(WholeFrameReason::Refused)
268}
269
270/// Every check's image, the three-panel one where it can be trusted and the
271/// whole frame otherwise, each with the line saying which and why.
272pub struct PanelImages {
273    /// The whole frames, and where every image is written.
274    whole: WholeFrames,
275    /// Each print's alignment verdict and last check, and the calibration.
276    alignments: Arc<Alignments>,
277    /// The configured camera's snapshot address: the stream every frame of a
278    /// print is of, an alert's included, which the camera's own feed relays.
279    camera_snapshot_url: Option<String>,
280}
281
282impl core::fmt::Debug for PanelImages {
283    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
284        formatter
285            .debug_struct("PanelImages")
286            .field("whole", &self.whole)
287            .field("camera_snapshot_url", &self.camera_snapshot_url)
288            .finish_non_exhaustive()
289    }
290}
291
292impl PanelImages {
293    /// The images of one state directory's frames.
294    #[must_use]
295    pub fn new(
296        state_dir: &Path,
297        alignments: Arc<Alignments>,
298        camera_snapshot_url: Option<String>,
299    ) -> Self {
300        Self {
301            whole: WholeFrames::under(state_dir),
302            alignments,
303            camera_snapshot_url,
304        }
305    }
306
307    /// The whole frame, with the line saying why.
308    fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
309        Ok(ShownImage {
310            path: self.whole.check_image(None, frame)?,
311            note: Some(whole_frame_note(reason)),
312        })
313    }
314
315    /// The three-panel image of one request of a print, or why it is shown
316    /// the whole frame instead.
317    fn composite(
318        &self,
319        print_id: PrintId,
320        request: &CheckImageRequest<'_>,
321        previous: Option<&PreviousCheck>,
322    ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
323        let Some(calibration) = self.alignments.calibration() else {
324            return Ok(Err(WholeFrameReason::NoCalibration));
325        };
326        let Some(url) = self.camera_snapshot_url.as_deref() else {
327            return Ok(Err(WholeFrameReason::NoStream));
328        };
329        let Some(plan) = &request.plan else {
330            return Ok(Err(WholeFrameReason::NoPosition));
331        };
332        let at = PlanAt {
333            index: &plan.index,
334            file_position_bytes: plan.file_position_bytes,
335        };
336        if at.index.object_at(at.file_position_bytes).is_none()
337            || at.index.object_outlines().is_empty()
338        {
339            return Ok(Err(WholeFrameReason::NoObject));
340        }
341        if at.index.layer_at(at.file_position_bytes).is_none() {
342            return Ok(Err(WholeFrameReason::NoLayer));
343        }
344        match self.alignments.print_alignment(print_id) {
345            PrintAlignment::Passed { .. } => {}
346            PrintAlignment::Pending => return Ok(Err(WholeFrameReason::AlignmentPending)),
347            PrintAlignment::Unavailable => {
348                return Ok(Err(WholeFrameReason::AlignmentUnavailable));
349            }
350            PrintAlignment::Failed { reason } => {
351                return Ok(Err(WholeFrameReason::AlignmentFailed(reason)));
352            }
353        }
354        let current = std::fs::read(request.frame)
355            .map_err(|error| format!("{} is unreadable: {error}", request.frame.display()))?;
356        // A previous frame gone from the store, or one that no longer decodes,
357        // is one the panel cannot show, which leaves panel 3 empty rather than
358        // the check without an image.
359        let earlier = previous.and_then(|check| {
360            std::fs::read(&check.frame)
361                .ok()
362                .filter(|bytes| whole_frame(bytes).is_ok())
363                .map(|bytes| (bytes, check.captured_at))
364        });
365        let composed = match compose_at(
366            at,
367            (&current, request.captured_at),
368            earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
369            url,
370            calibration,
371        ) {
372            Ok(composed) => composed,
373            // The current frame was judged whole by the vision port before it
374            // was stored, and the previous one was decoded above, so neither
375            // refusal is reached by a frame the camera gave; one that is is a
376            // check shown the stored frame, as any check image that cannot be
377            // made is, which `a check image that cannot be written` proves.
378            Err(WholeFrameReason::Refused(
379                ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
380            )) => return Err(detail),
381            Err(reason) => return Ok(Err(reason)),
382        };
383        let destination = self.composite_destination(request.frame, previous);
384        write_image(&self.whole.directory, &destination, &composed.jpeg)?;
385        Ok(Ok(ShownImage {
386            path: destination,
387            note: Some(composite_note(earlier.is_none())),
388        }))
389    }
390
391    /// Where the three-panel image of one stored frame, after one previous
392    /// check, is written: named for both, which name it uniquely.
393    fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
394        let named = |frame: &Path| {
395            let part = |part: Option<&std::ffi::OsStr>| {
396                part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
397            };
398            format!(
399                "{}-{}",
400                part(frame.parent().and_then(Path::file_name)),
401                part(frame.file_name())
402            )
403        };
404        let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
405        self.whole
406            .directory
407            .join(format!("{}-composite-after-{after}.jpg", named(frame)))
408    }
409}
410
411impl CheckImages for PanelImages {
412    fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
413        self.whole.check_image(print_id, frame)
414    }
415
416    fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
417        let Some(print_id) = request.print_id else {
418            return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
419        };
420        let previous = self.alignments.previous_check(print_id);
421        let shown = match self.composite(print_id, request, previous.as_ref())? {
422            Ok(composite) => composite,
423            Err(reason) => self.whole_frame(request.frame, &reason)?,
424        };
425        if request.made_for == ImageUse::Check {
426            self.alignments.record_check(
427                print_id,
428                &PreviousCheck {
429                    frame: request.frame.to_path_buf(),
430                    captured_at: request.captured_at,
431                },
432            );
433        }
434        Ok(shown)
435    }
436}