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//!
14//! A check shown the three-panel image is also measured against the newest
15//! earlier check's frame at least [`MIN_RISE_MM`] below it in the plan
16//! ([`measure_growth`]). When the parts this layer lays sit where that frame
17//! had them, carried down with the bed, the line says so
18//! ([`not_grown_note`]): a stall shows as a few pixels between a drawn line
19//! and a part's top, which the eye misreads, and the measurement does not.
20
21use std::path::{Path, PathBuf};
22use std::sync::atomic::{AtomicU64, Ordering};
23
24use std::sync::Arc;
25
26use printobserver_core::check_image::PlanPosition;
27use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
28use printobserver_panels::growth::MIN_RISE_MM;
29use printobserver_panels::{
30    CameraCalibration, CheckImage, CheckImageInputs, ComposeError, GrowthInputs,
31    WHOLE_FRAME_HEIGHT, WHOLE_FRAME_WIDTH, compose_check_image, measure_growth, whole_frame,
32};
33use printobserver_types::{PrintId, Timestamp};
34
35use crate::alignment::{AlignmentFailure, Alignments, CheckedFrame, PreviousCheck, PrintAlignment};
36
37/// How many scaled frames this process has begun writing, which names each
38/// write's partial file apart from any other's.
39static WRITES: AtomicU64 = AtomicU64::new(0);
40
41/// The directory under the state directory check images are written in.
42pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
43
44/// Every check shown the whole frame, scaled.
45#[derive(Debug, Clone)]
46pub struct WholeFrames {
47    /// Where the scaled frames are written.
48    directory: PathBuf,
49}
50
51impl WholeFrames {
52    /// Write scaled frames under one state directory.
53    #[must_use]
54    pub fn under(state_dir: &Path) -> Self {
55        Self {
56            directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
57        }
58    }
59
60    /// Where the scaled copy of one stored frame is written: named for the
61    /// stored frame's own directory and file, which name it uniquely.
62    fn destination(&self, frame: &Path) -> PathBuf {
63        let named = |part: Option<&std::ffi::OsStr>| {
64            part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
65        };
66        let parent = named(frame.parent().and_then(Path::file_name));
67        let file = named(frame.file_name());
68        self.directory.join(format!(
69            "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
70        ))
71    }
72}
73
74impl CheckImages for WholeFrames {
75    fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
76        let destination = self.destination(frame);
77        if destination.is_file() {
78            return Ok(destination);
79        }
80        let bytes = std::fs::read(frame)
81            .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
82        let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
83        if !scaled.scaled {
84            return Ok(frame.to_path_buf());
85        }
86        write_image(&self.directory, &destination, &scaled.jpeg)?;
87        Ok(destination)
88    }
89}
90
91/// Write one check image — a scaled frame or a three-panel image — under
92/// `directory` at `destination`, beside its name first
93/// and moved onto it, so a reader never opens a half-written image.
94fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
95    std::fs::create_dir_all(directory)
96        .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
97    let partial = destination.with_extension(format!(
98        "{}-{}.partial",
99        std::process::id(),
100        WRITES.fetch_add(1, Ordering::Relaxed)
101    ));
102    let written =
103        std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
104    written.map_err(|error| {
105        // Whatever was written is no image a reader may open.
106        let _ = std::fs::remove_file(&partial);
107        format!("{} cannot be written: {error}", destination.display())
108    })
109}
110
111/// The first words of every line saying a check was shown the three-panel
112/// image, which the real-print suite's record reads the image's kind from.
113pub const COMPOSITE_NOTE: &str = "the three-panel check image";
114
115/// The first words of every line saying a check was shown the whole frame.
116pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
117
118/// Why a check is shown the whole frame rather than the three-panel image.
119#[derive(Debug, Clone, PartialEq)]
120pub enum WholeFrameReason {
121    /// No print is named: a look at the printer, before, between or after
122    /// prints, a start's bed check among them.
123    NoPrint,
124    /// No camera calibration is configured.
125    NoCalibration,
126    /// No camera snapshot address is configured, so the frame's stream is
127    /// unknown.
128    NoStream,
129    /// The job is not the print's file, reported no position, or its file has
130    /// no index.
131    NoPosition,
132    /// The print's G-code names no extruded object, or none laid yet, at the
133    /// check's file position.
134    NoObject,
135    /// It names no layer there.
136    NoLayer,
137    /// The layer's planned toolpath could not be read from the print's spool.
138    ToolpathUnread(String),
139    /// The print's first-layer alignment is not decided yet.
140    AlignmentPending,
141    /// The print's G-code lays no object to align.
142    AlignmentUnavailable,
143    /// The print's first-layer alignment failed.
144    AlignmentFailed(AlignmentFailure),
145    /// The composer refused this frame.
146    Refused(ComposeError),
147}
148
149impl core::fmt::Display for WholeFrameReason {
150    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151        match self {
152            Self::NoPrint => formatter
153                .write_str("no print is named, so there is no planned toolpath to draw on it"),
154            Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
155            Self::NoStream => formatter.write_str(
156                "no camera snapshot address is configured, so the frame's stream is unknown",
157            ),
158            Self::NoPosition => formatter.write_str(
159                "the print's G-code index gives no file position for this check",
160            ),
161            Self::NoObject => formatter.write_str(
162                "the print's G-code names no extruded object laid at this point",
163            ),
164            Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
165            Self::ToolpathUnread(detail) => write!(
166                formatter,
167                "the layer's planned toolpath could not be read from the print's spool: {detail}"
168            ),
169            Self::AlignmentPending => formatter.write_str(
170                "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
171            ),
172            Self::AlignmentUnavailable => {
173                formatter.write_str("the print's G-code lays no object to align")
174            }
175            Self::AlignmentFailed(AlignmentFailure::Offset { offset_px }) => write!(
176                formatter,
177                "the print's first-layer alignment failed: the printed first layer lies {offset_px:.1} px from where the calibration projects it"
178            ),
179            Self::AlignmentFailed(AlignmentFailure::Resolution { expected, got }) => write!(
180                formatter,
181                "the print's first-layer alignment failed: the camera's frames are {}x{} and the calibration's {}x{}",
182                got[0], got[1], expected[0], expected[1]
183            ),
184            Self::AlignmentFailed(AlignmentFailure::Stream) => formatter.write_str(
185                "the print's first-layer alignment failed: the camera is not the stream the calibration was fitted on",
186            ),
187            Self::Refused(error) => error.fmt(formatter),
188        }
189    }
190}
191
192/// The line saying a check was shown the whole frame, and why.
193#[must_use]
194pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
195    format!(
196        "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}"
197    )
198}
199
200/// What a check's note says of the drawing before it says what a part off it
201/// means: an agent shown a part off its walls otherwise explains the
202/// difference as the camera or the bed having shifted in view.
203const CAMERA_HOLDS: &str = "the camera does not shift in regular operation and the drawing already accounts for the bed's travel, so ";
204
205/// The line saying a check or a look was shown the three-panel image of the
206/// frame captured at `current_at`, beside the frame `previous_at` names: panel
207/// 3 empty when no earlier check's frame is at hand — the print's first check,
208/// or one whose earlier frame is gone from the store.
209///
210/// A check's names which frame each panel is and when each was captured, and
211/// says what the skill says: the camera does not shift and the drawing follows
212/// the bed, so a part off it has moved unless there is strong evidence
213/// otherwise, and no later frame undoes it. A turn handed a check's image decides on it, with no look to
214/// stall on, so this is what it decides from. A look's says only what each
215/// panel is.
216#[must_use]
217pub fn composite_note(
218    made_for: ImageUse,
219    current_at: Timestamp,
220    previous_at: Option<Timestamp>,
221) -> String {
222    let (current, previous, moved) = match (made_for, previous_at) {
223        (ImageUse::Look, at) => (
224            "this layer's planned toolpath drawn on the frame".to_owned(),
225            if at.is_none() {
226                "panel 3 empty, no earlier check's frame being at hand".to_owned()
227            } else {
228                "panel 3 the previous check's frame".to_owned()
229            },
230            String::new(),
231        ),
232        (ImageUse::Check, None) => (
233            format!(
234                "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
235            ),
236            "panel 3 empty, no earlier check's frame being at hand".to_owned(),
237            format!(
238                "; {CAMERA_HOLDS}a part off its drawn walls in panel 1 has moved unless there is strong evidence otherwise, and no later frame undoes that"
239            ),
240        ),
241        (ImageUse::Check, Some(at)) => (
242            format!(
243                "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
244            ),
245            format!("panel 3 the previous check's frame, captured {at}"),
246            format!(
247                "; {CAMERA_HOLDS}a part off its drawn walls in panel 1, or moved since panel 3, has moved unless there is strong evidence otherwise, and no later frame undoes that"
248            ),
249        ),
250    };
251    format!(
252        "{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part being printed, {previous}{moved}",
253        printobserver_panels::compose::PANEL_WIDTH,
254        printobserver_panels::compose::IMAGE_HEIGHT
255    )
256}
257
258/// What a check's line adds when the measurement finds the parts this layer
259/// lays have not grown since the frame captured at `since`, `rise_mm` lower in
260/// the plan: the skill's own words for it, `not risen as planned`.
261#[must_use]
262pub fn not_grown_note(since: Timestamp, rise_mm: f64) -> String {
263    format!(
264        "; measured against the check frame captured {since}, {rise_mm:.1} mm lower in the plan: the parts this layer lays have not risen as planned, sitting where that frame had them, carried down with the bed, so nothing has been laid on them since"
265    )
266}
267
268/// The print's height in its plan at a check's position.
269fn plan_z(plan: &PlanPosition) -> Option<f64> {
270    plan.index
271        .layer_at(plan.file_position_bytes)
272        .and_then(|layer| plan.index.layer_z_mm(layer))
273}
274
275/// What a check image is composed from, beyond the frames: the print's plan at
276/// one file position.
277#[derive(Debug, Clone, Copy)]
278pub struct PlanAt<'a> {
279    /// The print's G-code index, its toolpaths read from its spool.
280    pub index: &'a GcodeIndex,
281    /// The check's file position.
282    pub file_position_bytes: u64,
283}
284
285/// Compose the three-panel check image of one frame at one file position, as
286/// every check of a print whose alignment passed is shown it: the active
287/// object at that position, the layer there — and, when that layer lays
288/// supports alone, the nearest object layer below it — over the frame, with
289/// `previous` as panel 3.
290///
291/// # Errors
292///
293/// [`WholeFrameReason`] naming what the index lacks at that position, or the
294/// composer's own refusal.
295pub fn compose_at(
296    plan: PlanAt<'_>,
297    current: (&[u8], Timestamp),
298    previous: Option<(&[u8], Timestamp)>,
299    camera_snapshot_url: &str,
300    calibration: &CameraCalibration,
301) -> Result<CheckImage, WholeFrameReason> {
302    let index = plan.index;
303    let position = plan.file_position_bytes;
304    let active_object = index
305        .object_at(position)
306        .filter(|object| *object < index.object_outlines().len())
307        .ok_or(WholeFrameReason::NoObject)?;
308    let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
309    let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
310    let unread =
311        |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
312    let toolpath = index.layer_toolpath(layer).map_err(unread)?;
313    let below = if toolpath.carries_object_extrusion() {
314        None
315    } else {
316        index
317            .object_layer_at_or_below(layer)
318            .map(|below| index.layer_toolpath(below))
319            .transpose()
320            .map_err(unread)?
321    };
322    compose_check_image(&CheckImageInputs {
323        current_jpeg: current.0,
324        current_at: current.1,
325        camera_snapshot_url,
326        previous,
327        outlines: index.object_outlines(),
328        active_object,
329        toolpath: &toolpath,
330        object_layer_below: below.as_ref(),
331        print_z_mm,
332        calibration,
333    })
334    .map_err(WholeFrameReason::Refused)
335}
336
337/// Every check's image, the three-panel one where it can be trusted and the
338/// whole frame otherwise, each with the line saying which and why.
339pub struct PanelImages {
340    /// The whole frames, and where every image is written.
341    whole: WholeFrames,
342    /// Each print's alignment verdict and last check, and the calibration.
343    alignments: Arc<Alignments>,
344    /// The configured camera's snapshot address: the stream every frame of a
345    /// print is of, an alert's included, which the camera's own feed relays.
346    camera_snapshot_url: Option<String>,
347}
348
349impl core::fmt::Debug for PanelImages {
350    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
351        formatter
352            .debug_struct("PanelImages")
353            .field("whole", &self.whole)
354            .field("camera_snapshot_url", &self.camera_snapshot_url)
355            .finish_non_exhaustive()
356    }
357}
358
359impl PanelImages {
360    /// The images of one state directory's frames.
361    #[must_use]
362    pub fn new(
363        state_dir: &Path,
364        alignments: Arc<Alignments>,
365        camera_snapshot_url: Option<String>,
366    ) -> Self {
367        Self {
368            whole: WholeFrames::under(state_dir),
369            alignments,
370            camera_snapshot_url,
371        }
372    }
373
374    /// The whole frame, with the line saying why.
375    fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
376        Ok(ShownImage {
377            path: self.whole.check_image(None, frame)?,
378            note: Some(whole_frame_note(reason)),
379            composite: false,
380        })
381    }
382
383    /// The three-panel image of one request of a print, or why it is shown
384    /// the whole frame instead.
385    fn composite(
386        &self,
387        print_id: PrintId,
388        request: &CheckImageRequest<'_>,
389        previous: Option<&PreviousCheck>,
390    ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
391        let Some(calibration) = self.alignments.calibration() else {
392            return Ok(Err(WholeFrameReason::NoCalibration));
393        };
394        let Some(url) = self.camera_snapshot_url.as_deref() else {
395            return Ok(Err(WholeFrameReason::NoStream));
396        };
397        let Some(plan) = &request.plan else {
398            return Ok(Err(WholeFrameReason::NoPosition));
399        };
400        let at = PlanAt {
401            index: &plan.index,
402            file_position_bytes: plan.file_position_bytes,
403        };
404        if at.index.object_at(at.file_position_bytes).is_none()
405            || at.index.object_outlines().is_empty()
406        {
407            return Ok(Err(WholeFrameReason::NoObject));
408        }
409        if at.index.layer_at(at.file_position_bytes).is_none() {
410            return Ok(Err(WholeFrameReason::NoLayer));
411        }
412        match self.alignments.print_alignment(print_id) {
413            PrintAlignment::Passed { .. } => {}
414            PrintAlignment::Pending => return Ok(Err(WholeFrameReason::AlignmentPending)),
415            PrintAlignment::Unavailable => {
416                return Ok(Err(WholeFrameReason::AlignmentUnavailable));
417            }
418            PrintAlignment::Failed { reason } => {
419                return Ok(Err(WholeFrameReason::AlignmentFailed(reason)));
420            }
421        }
422        let current = std::fs::read(request.frame)
423            .map_err(|error| format!("{} is unreadable: {error}", request.frame.display()))?;
424        // A previous frame gone from the store, or one that no longer decodes,
425        // is one the panel cannot show, which leaves panel 3 empty rather than
426        // the check without an image.
427        let earlier = previous.and_then(|check| {
428            std::fs::read(&check.frame)
429                .ok()
430                .filter(|bytes| whole_frame(bytes).is_ok())
431                .map(|bytes| (bytes, check.captured_at))
432        });
433        let composed = match compose_at(
434            at,
435            (&current, request.captured_at),
436            earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
437            url,
438            calibration,
439        ) {
440            Ok(composed) => composed,
441            // The current frame was judged whole by the vision port before it
442            // was stored, and the previous one was decoded above, so neither
443            // refusal is reached by a frame the camera gave; one that is is a
444            // check shown the stored frame, as any check image that cannot be
445            // made is, which `a check image that cannot be written` proves.
446            Err(WholeFrameReason::Refused(
447                ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
448            )) => return Err(detail),
449            Err(reason) => return Ok(Err(reason)),
450        };
451        let destination = self.composite_destination(request.frame, previous);
452        write_image(&self.whole.directory, &destination, &composed.jpeg)?;
453        let mut note = composite_note(
454            request.made_for,
455            request.captured_at,
456            earlier.as_ref().map(|(_, at)| *at),
457        );
458        if request.made_for == ImageUse::Check
459            && let Some(clause) = self.growth_clause(print_id, plan, &current, url, calibration)
460        {
461            note.push_str(&clause);
462        }
463        Ok(Ok(ShownImage {
464            path: destination,
465            note: Some(note),
466            composite: true,
467        }))
468    }
469
470    /// What a check's line adds of whether the parts grew: the
471    /// [`not_grown_note`] when the measurement against the newest earlier
472    /// check's frame at least [`MIN_RISE_MM`] below finds they did not, and
473    /// nothing otherwise — no such frame, one gone from the store, a layer
474    /// laying supports alone, or a measurement that found growth or could not
475    /// tell. Each measurement made is said on the log.
476    fn growth_clause(
477        &self,
478        print_id: PrintId,
479        plan: &PlanPosition,
480        current: &[u8],
481        url: &str,
482        calibration: &CameraCalibration,
483    ) -> Option<String> {
484        let layer = plan.index.layer_at(plan.file_position_bytes)?;
485        let print_z_mm = plan.index.layer_z_mm(layer)?;
486        let reference = self
487            .alignments
488            .growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
489        let earlier = std::fs::read(&reference.frame).ok()?;
490        let toolpath = plan.index.layer_toolpath(layer).ok()?;
491        let measured = measure_growth(&GrowthInputs {
492            earlier_jpeg: &earlier,
493            earlier_print_z_mm: reference.print_z_mm,
494            current_jpeg: current,
495            current_print_z_mm: print_z_mm,
496            camera_snapshot_url: url,
497            toolpath: &toolpath,
498            calibration,
499        })
500        .ok()??;
501        let not_grown = measured.not_grown();
502        eprintln!(
503            "printobserver: print {print_id}: growth from Z {:.1} ({}) to Z {print_z_mm:.1}: carried {:.2}, held {:.2}, {:.0}% carried over {} samples {:.1} px apart: {}",
504            reference.print_z_mm,
505            reference.captured_at,
506            measured.carried,
507            measured.held,
508            measured.carried_share * 100.0,
509            measured.samples,
510            measured.separation_px,
511            if not_grown { "not grown" } else { "no verdict" }
512        );
513        not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
514    }
515
516    /// Where the three-panel image of one stored frame, after one previous
517    /// check, is written: named for both, which name it uniquely.
518    fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
519        let named = |frame: &Path| {
520            let part = |part: Option<&std::ffi::OsStr>| {
521                part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
522            };
523            format!(
524                "{}-{}",
525                part(frame.parent().and_then(Path::file_name)),
526                part(frame.file_name())
527            )
528        };
529        let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
530        self.whole
531            .directory
532            .join(format!("{}-composite-after-{after}.jpg", named(frame)))
533    }
534}
535
536impl CheckImages for PanelImages {
537    fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
538        self.whole.check_image(print_id, frame)
539    }
540
541    fn composes(&self, print_id: PrintId) -> bool {
542        self.alignments.calibration().is_some()
543            && self.camera_snapshot_url.is_some()
544            && matches!(
545                self.alignments.print_alignment(print_id),
546                PrintAlignment::Passed { .. }
547            )
548    }
549
550    fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
551        let Some(print_id) = request.print_id else {
552            return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
553        };
554        let previous = self.alignments.previous_check(print_id);
555        let shown = match self.composite(print_id, request, previous.as_ref())? {
556            Ok(composite) => composite,
557            Err(reason) => self.whole_frame(request.frame, &reason)?,
558        };
559        if request.made_for == ImageUse::Check {
560            self.alignments.record_check(
561                print_id,
562                &PreviousCheck {
563                    frame: request.frame.to_path_buf(),
564                    captured_at: request.captured_at,
565                },
566            );
567            if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
568                self.alignments.record_checked_frame(
569                    print_id,
570                    CheckedFrame {
571                        frame: request.frame.to_path_buf(),
572                        captured_at: request.captured_at,
573                        print_z_mm,
574                    },
575                    MIN_RISE_MM,
576                );
577            }
578        }
579        Ok(shown)
580    }
581}