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 printobserver_panels::{InconclusiveReason, ViewCorrection, ViewOutcome};
36use printobserver_supervisor_api::{ImageFallback, WholeFrameReasonCode};
37
38use crate::alignment::{
39    AlignmentFailure, AlignmentJudging, Alignments, CheckedFrame, Judged, Judging, LastCheckImage,
40    PreviousCheck, PrintAlignment, failure_sentence,
41};
42
43/// How many scaled frames this process has begun writing, which names each
44/// write's partial file apart from any other's.
45static WRITES: AtomicU64 = AtomicU64::new(0);
46
47/// The directory under the state directory check images are written in.
48pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
49
50/// Every check shown the whole frame, scaled.
51#[derive(Debug, Clone)]
52pub struct WholeFrames {
53    /// Where the scaled frames are written.
54    directory: PathBuf,
55}
56
57impl WholeFrames {
58    /// Write scaled frames under one state directory.
59    #[must_use]
60    pub fn under(state_dir: &Path) -> Self {
61        Self {
62            directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
63        }
64    }
65
66    /// Where the scaled copy of one stored frame is written: named for the
67    /// stored frame's own directory and file, which name it uniquely.
68    fn destination(&self, frame: &Path) -> PathBuf {
69        let named = |part: Option<&std::ffi::OsStr>| {
70            part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
71        };
72        let parent = named(frame.parent().and_then(Path::file_name));
73        let file = named(frame.file_name());
74        self.directory.join(format!(
75            "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
76        ))
77    }
78}
79
80impl CheckImages for WholeFrames {
81    fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
82        let destination = self.destination(frame);
83        if destination.is_file() {
84            return Ok(destination);
85        }
86        let bytes = std::fs::read(frame)
87            .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
88        let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
89        if !scaled.scaled {
90            return Ok(frame.to_path_buf());
91        }
92        write_image(&self.directory, &destination, &scaled.jpeg)?;
93        Ok(destination)
94    }
95}
96
97/// Write one check image — a scaled frame or a three-panel image — under
98/// `directory` at `destination`, beside its name first
99/// and moved onto it, so a reader never opens a half-written image.
100fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
101    std::fs::create_dir_all(directory)
102        .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
103    let partial = destination.with_extension(format!(
104        "{}-{}.partial",
105        std::process::id(),
106        WRITES.fetch_add(1, Ordering::Relaxed)
107    ));
108    let written =
109        std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
110    written.map_err(|error| {
111        // Whatever was written is no image a reader may open.
112        let _ = std::fs::remove_file(&partial);
113        format!("{} cannot be written: {error}", destination.display())
114    })
115}
116
117/// The first words of every line saying a check was shown the three-panel
118/// image, which the real-print suite's record reads the image's kind from.
119pub const COMPOSITE_NOTE: &str = "the three-panel check image";
120
121/// The first words of every line saying a check was shown the whole frame.
122pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
123
124/// Why a check is shown the whole frame rather than the three-panel image.
125#[derive(Debug, Clone, PartialEq)]
126pub enum WholeFrameReason {
127    /// No print is named: a look at the printer, before, between or after
128    /// prints, a start's bed check among them.
129    NoPrint,
130    /// No camera calibration is configured.
131    NoCalibration,
132    /// No camera snapshot address is configured, so the frame's stream is
133    /// unknown.
134    NoStream,
135    /// The job is not the print's file, reported no position, or its file has
136    /// no index.
137    NoPosition,
138    /// The print's G-code names no extruded object, or none laid yet, at the
139    /// check's file position.
140    NoObject,
141    /// It names no layer there.
142    NoLayer,
143    /// The layer's planned toolpath could not be read from the print's spool.
144    ToolpathUnread(String),
145    /// The print's first-layer alignment is not decided yet.
146    AlignmentPending,
147    /// The frame the print's first-layer alignment was last judged on could
148    /// not tell where the layer lies; a later check's is judged again.
149    AlignmentInconclusive(InconclusiveReason),
150    /// The print's G-code lays no object to align.
151    AlignmentUnavailable,
152    /// The print's first-layer alignment failed.
153    AlignmentFailed(AlignmentFailure),
154    /// Fewer than two landmarks are found, so whether the camera shifted is
155    /// unknown.
156    LandmarksNotFound(String),
157    /// The camera moved since the print's correction was taken.
158    ViewRefitRejected(String),
159    /// The landmarks show the camera has moved since its calibration, so the
160    /// plan cannot be drawn reliably on its frames, whatever correction a pass
161    /// took: a translation cannot repair a camera that has turned.
162    CalibrationStale,
163    /// The frame is not the calibration's size or stream.
164    FrameMismatch(String),
165    /// The printer reports the print paused, its bed moved off the plan's
166    /// height.
167    Paused,
168    /// The composer refused this frame.
169    Refused(ComposeError),
170}
171
172impl WholeFrameReason {
173    /// The reason as a code.
174    #[must_use]
175    pub const fn code(&self) -> WholeFrameReasonCode {
176        match self {
177            Self::NoPrint => WholeFrameReasonCode::NoPrint,
178            Self::NoCalibration => WholeFrameReasonCode::NoCalibration,
179            Self::NoStream => WholeFrameReasonCode::NoStream,
180            Self::NoPosition => WholeFrameReasonCode::NoPosition,
181            Self::NoObject => WholeFrameReasonCode::NoObject,
182            Self::NoLayer => WholeFrameReasonCode::NoLayer,
183            Self::ToolpathUnread(_) => WholeFrameReasonCode::ToolpathUnread,
184            Self::AlignmentPending => WholeFrameReasonCode::AlignmentPending,
185            Self::AlignmentInconclusive(_) => WholeFrameReasonCode::AlignmentInconclusive,
186            Self::AlignmentUnavailable => WholeFrameReasonCode::AlignmentUnavailable,
187            Self::AlignmentFailed(_) => WholeFrameReasonCode::AlignmentFailed,
188            Self::LandmarksNotFound(_) | Self::Refused(ComposeError::DriftUnverified) => {
189                WholeFrameReasonCode::LandmarksNotFound
190            }
191            Self::ViewRefitRejected(_) | Self::Refused(ComposeError::CameraMoved { .. }) => {
192                WholeFrameReasonCode::ViewRefitRejected
193            }
194            Self::FrameMismatch(_) | Self::Refused(ComposeError::FrameMismatch { .. }) => {
195                WholeFrameReasonCode::FrameMismatch
196            }
197            Self::CalibrationStale => WholeFrameReasonCode::CalibrationStale,
198            Self::Paused => WholeFrameReasonCode::Paused,
199            Self::Refused(_) => WholeFrameReasonCode::Refused,
200        }
201    }
202}
203
204impl core::fmt::Display for WholeFrameReason {
205    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
206        match self {
207            Self::NoPrint => formatter
208                .write_str("no print is named, so there is no planned toolpath to draw on it"),
209            Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
210            Self::NoStream => formatter.write_str(
211                "no camera snapshot address is configured, so the frame's stream is unknown",
212            ),
213            Self::NoPosition => formatter.write_str(
214                "the print's G-code index gives no file position for this check",
215            ),
216            Self::NoObject => formatter.write_str(
217                "the print's G-code names no extruded object laid at this point",
218            ),
219            Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
220            Self::ToolpathUnread(detail) => write!(
221                formatter,
222                "the layer's planned toolpath could not be read from the print's spool: {detail}"
223            ),
224            Self::AlignmentPending => formatter.write_str(
225                "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
226            ),
227            Self::AlignmentInconclusive(why) => write!(
228                formatter,
229                "the print's first-layer alignment is inconclusive on the frame judged last: {}, so a later check's frame is judged again; this is no evidence of a defect",
230                match why {
231                    InconclusiveReason::Covered => "the toolhead covers the part, which sits hidden under the head on this frame: bare sheet beside the head alone is no sign the part is gone, but a part seen moved, loose or in spaghetti is",
232                    InconclusiveReason::NotClearlyFound => "the printed first layer was not clearly found",
233                }
234            ),
235            Self::AlignmentUnavailable => {
236                formatter.write_str("the print's G-code lays no object to align")
237            }
238            Self::AlignmentFailed(failure) => write!(
239                formatter,
240                "the print's first-layer alignment failed: {}",
241                failure_sentence(failure)
242            ),
243            Self::LandmarksNotFound(reason) | Self::ViewRefitRejected(reason) | Self::FrameMismatch(reason) => {
244                formatter.write_str(reason)
245            }
246            Self::CalibrationStale => formatter.write_str(CALIBRATION_STALE),
247            Self::Paused => formatter.write_str(
248                "the printer reports the print paused, so its bed may stand off the plan's height and nothing is drawn",
249            ),
250            Self::Refused(error) => error.fmt(formatter),
251        }
252    }
253}
254
255/// Why a check of a camera that has moved since its calibration is shown the
256/// whole frame.
257pub const CALIBRATION_STALE: &str = "the camera has moved since its calibration, so the outline cannot be drawn reliably; recalibrate this camera";
258
259/// How far the plan may rise, in millimetres, past a frame a check is compared
260/// against before a part not plainly higher on a whole frame shown for the
261/// camera's own sake is grounds to pause. On the two-colour print's stale
262/// camera, the box's rise of 1.8 and 4.0 mm was read by eye as none, and the
263/// healthy print paused; a part that stops growing for longer than this still
264/// is.
265pub const UNSEEN_RISE_BOUND_MM: f64 = 5.0;
266
267/// The line saying a check was shown the whole frame, and why.
268///
269/// A whole frame shown because the camera moved since its calibration, or
270/// because the first layer was not clearly found, carries the bound
271/// [`UNSEEN_RISE_BOUND_MM`] on judging a rise by eye; every other whole frame
272/// keeps the skill's own rule.
273#[must_use]
274pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
275    let bound = match reason {
276        WholeFrameReason::CalibrationStale | WholeFrameReason::AlignmentInconclusive(_) => format!(
277            "; on this frame a part that is not plainly higher is no grounds to pause on its own until the plan's rise since the frame it is compared against exceeds {UNSEEN_RISE_BOUND_MM:.0} mm"
278        ),
279        _ => String::new(),
280    };
281    format!(
282        "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}{bound}"
283    )
284}
285
286/// What a check's note says of the drawing before it says what a part off it
287/// means: an agent shown a part off its walls otherwise explains the
288/// difference as the camera or the bed having shifted in view.
289const CAMERA_HOLDS: &str = "the camera does not shift in regular operation and the drawing already accounts for the bed's travel, so ";
290
291/// The line saying a check or a look was shown the three-panel image of the
292/// frame captured at `current_at`, beside the frame `previous_at` names: panel
293/// 3 empty when no earlier check's frame is at hand — the print's first check,
294/// or one whose earlier frame is gone from the store.
295///
296/// A check's names which frame each panel is and when each was captured, and
297/// says what the skill says: the camera does not shift and the drawing follows
298/// the bed, so a part off it has moved unless there is strong evidence
299/// otherwise, and no later frame undoes it. A turn handed a check's image decides on it, with no look to
300/// stall on, so this is what it decides from. A look's says only what each
301/// panel is.
302#[must_use]
303pub fn composite_note(
304    made_for: ImageUse,
305    current_at: Timestamp,
306    previous_at: Option<Timestamp>,
307) -> String {
308    let (current, previous, moved) = match (made_for, previous_at) {
309        (ImageUse::Look, at) => (
310            "this layer's planned toolpath drawn on the frame".to_owned(),
311            if at.is_none() {
312                "panel 3 empty, no earlier check's frame being at hand".to_owned()
313            } else {
314                "panel 3 the previous check's frame".to_owned()
315            },
316            String::new(),
317        ),
318        (ImageUse::Check, None) => (
319            format!(
320                "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
321            ),
322            "panel 3 empty, no earlier check's frame being at hand".to_owned(),
323            format!(
324                "; {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"
325            ),
326        ),
327        (ImageUse::Check, Some(at)) => (
328            format!(
329                "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
330            ),
331            format!("panel 3 the previous check's frame, captured {at}"),
332            format!(
333                "; {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"
334            ),
335        ),
336    };
337    format!(
338        "{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part being printed, {previous}{moved}",
339        printobserver_panels::compose::PANEL_WIDTH,
340        printobserver_panels::compose::IMAGE_HEIGHT
341    )
342}
343
344/// What a check's line adds when the measurement finds the parts this layer
345/// lays have not grown since the frame captured at `since`, `rise_mm` lower in
346/// the plan: the skill's own words for it, `not risen as planned`.
347#[must_use]
348pub fn not_grown_note(since: Timestamp, rise_mm: f64) -> String {
349    format!(
350        "; 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"
351    )
352}
353
354/// The print's height in its plan at a check's position.
355fn plan_z(plan: &PlanPosition) -> Option<f64> {
356    plan.index
357        .layer_at(plan.file_position_bytes)
358        .and_then(|layer| plan.index.layer_z_mm(layer))
359}
360
361/// What a check image is composed from, beyond the frames: the print's plan at
362/// one file position.
363#[derive(Debug, Clone, Copy)]
364pub struct PlanAt<'a> {
365    /// The print's G-code index, its toolpaths read from its spool.
366    pub index: &'a GcodeIndex,
367    /// The check's file position.
368    pub file_position_bytes: u64,
369}
370
371/// Compose the three-panel check image of one frame at one file position, as
372/// every check of a print whose alignment passed is shown it, through the
373/// print's correction when one is given: the active
374/// object at that position, the layer there — and, when that layer lays
375/// supports alone, the nearest object layer below it — over the frame, with
376/// `previous` as panel 3.
377///
378/// # Errors
379///
380/// [`WholeFrameReason`] naming what the index lacks at that position, or the
381/// composer's own refusal.
382pub fn compose_at(
383    plan: PlanAt<'_>,
384    current: (&[u8], Timestamp),
385    previous: Option<(&[u8], Timestamp)>,
386    camera_snapshot_url: &str,
387    calibration: &CameraCalibration,
388    correction: Option<&ViewCorrection>,
389) -> Result<CheckImage, WholeFrameReason> {
390    let index = plan.index;
391    let position = plan.file_position_bytes;
392    let active_object = index
393        .object_at(position)
394        .filter(|object| *object < index.object_outlines().len())
395        .ok_or(WholeFrameReason::NoObject)?;
396    let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
397    let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
398    let unread =
399        |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
400    let toolpath = index.layer_toolpath(layer).map_err(unread)?;
401    let below = if toolpath.carries_object_extrusion() {
402        None
403    } else {
404        index
405            .object_layer_at_or_below(layer)
406            .map(|below| index.layer_toolpath(below))
407            .transpose()
408            .map_err(unread)?
409    };
410    compose_check_image(&CheckImageInputs {
411        current_jpeg: current.0,
412        current_at: current.1,
413        camera_snapshot_url,
414        previous,
415        outlines: index.object_outlines(),
416        active_object,
417        toolpath: &toolpath,
418        object_layer_below: below.as_ref(),
419        print_z_mm,
420        calibration,
421        correction,
422    })
423    .map_err(WholeFrameReason::Refused)
424}
425
426/// Why a judged frame of a print whose plan places it may not be drawn on.
427///
428/// A frame whose landmarks have moved from the calibration is drawn on not at
429/// all, though they agree with the correction in force: on the first shifted
430/// print the projection stood 1 to 31 px off the part, growing with height and
431/// toward the back, which no translation removes.
432fn refusal_of(judged: &Judged) -> Result<(), WholeFrameReason> {
433    if let Some(reason) = &judged.rejected {
434        return Err(WholeFrameReason::ViewRefitRejected(reason.clone()));
435    }
436    if judged.camera_check.is_some() {
437        return refusal_under_check(judged);
438    }
439    match &judged.alignment {
440        PrintAlignment::Passed { .. } => {}
441        PrintAlignment::Pending => {
442            return Err(judged.inconclusive.map_or(
443                WholeFrameReason::AlignmentPending,
444                WholeFrameReason::AlignmentInconclusive,
445            ));
446        }
447        PrintAlignment::Unavailable => return Err(WholeFrameReason::AlignmentUnavailable),
448        PrintAlignment::Failed { reason } => {
449            return Err(WholeFrameReason::AlignmentFailed(reason.clone()));
450        }
451    }
452    if let Some(reason) = &judged.mismatch {
453        return Err(WholeFrameReason::FrameMismatch(reason.clone()));
454    }
455    let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
456    match &judged.view {
457        Some((ViewOutcome::LandmarksNotFound, reason)) => {
458            Err(WholeFrameReason::LandmarksNotFound(said(reason)))
459        }
460        Some((ViewOutcome::ViewRefitRejected, reason)) => {
461            Err(WholeFrameReason::ViewRefitRejected(said(reason)))
462        }
463        Some((ViewOutcome::FrameMismatch, reason)) => {
464            Err(WholeFrameReason::FrameMismatch(said(reason)))
465        }
466        Some((ViewOutcome::Refit, _)) => Err(WholeFrameReason::CalibrationStale),
467        Some((ViewOutcome::Unshifted, _)) | None => Ok(()),
468    }
469}
470
471/// Why a frame of a print started under a camera check may not be drawn on:
472/// only a frame that is not the calibration's, or whose landmarks the check's
473/// reference no longer finds, or finds moved again beyond it. Its first-layer
474/// verdict, whatever it is, is no reason: the check already placed the
475/// projection, and a first-layer search scores a toolhead over a small part as
476/// readily as the part.
477fn refusal_under_check(judged: &Judged) -> Result<(), WholeFrameReason> {
478    if let Some(reason) = &judged.mismatch {
479        return Err(WholeFrameReason::FrameMismatch(reason.clone()));
480    }
481    let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
482    match &judged.view {
483        Some((ViewOutcome::LandmarksNotFound, reason)) => {
484            Err(WholeFrameReason::LandmarksNotFound(said(reason)))
485        }
486        Some((ViewOutcome::ViewRefitRejected, reason)) => {
487            Err(WholeFrameReason::ViewRefitRejected(said(reason)))
488        }
489        Some((ViewOutcome::FrameMismatch, reason)) => {
490            Err(WholeFrameReason::FrameMismatch(said(reason)))
491        }
492        Some((ViewOutcome::Refit | ViewOutcome::Unshifted, _)) | None => Ok(()),
493    }
494}
495
496/// One judged frame whose image is chosen.
497#[derive(Debug, Clone, Copy)]
498pub struct Shown<'a> {
499    /// Where the stored frame is.
500    pub frame: &'a Path,
501    /// When it was captured.
502    pub captured_at: Timestamp,
503    /// What the image is for.
504    pub made_for: ImageUse,
505    /// Where the print stood in its plan.
506    pub plan: Option<&'a PlanPosition>,
507    /// Whether the printer reported the print paused.
508    pub paused: bool,
509}
510
511/// Every check's image, the three-panel one where it can be trusted and the
512/// whole frame otherwise, each with the line saying which and why.
513pub struct PanelImages {
514    /// The whole frames, and where every image is written.
515    whole: WholeFrames,
516    /// Each print's alignment verdict and last check, and the calibration.
517    alignments: Arc<Alignments>,
518    /// The configured camera's snapshot address: the stream every frame of a
519    /// print is of, an alert's included, which the camera's own feed relays.
520    camera_snapshot_url: Option<String>,
521}
522
523impl core::fmt::Debug for PanelImages {
524    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
525        formatter
526            .debug_struct("PanelImages")
527            .field("whole", &self.whole)
528            .field("camera_snapshot_url", &self.camera_snapshot_url)
529            .finish_non_exhaustive()
530    }
531}
532
533impl PanelImages {
534    /// The images of one state directory's frames.
535    #[must_use]
536    pub fn new(
537        state_dir: &Path,
538        alignments: Arc<Alignments>,
539        camera_snapshot_url: Option<String>,
540    ) -> Self {
541        Self {
542            whole: WholeFrames::under(state_dir),
543            alignments,
544            camera_snapshot_url,
545        }
546    }
547
548    /// The camera calibration in force, when one is configured.
549    #[must_use]
550    pub fn calibration(&self) -> Option<&CameraCalibration> {
551        self.alignments.calibration()
552    }
553
554    /// Write the frame a camera check drew its fit on beside every check
555    /// image, named for the check, and answer where it is.
556    ///
557    /// # Errors
558    ///
559    /// Why it could not be written.
560    pub fn write_camera_check_image(
561        &self,
562        camera_check: printobserver_core::CameraCheckId,
563        jpeg: &[u8],
564    ) -> Result<PathBuf, String> {
565        let destination = self
566            .whole
567            .directory
568            .join(format!("camera-check-{camera_check}.jpg"));
569        write_image(&self.whole.directory, &destination, jpeg)?;
570        Ok(destination)
571    }
572
573    /// One print's first-layer alignment as it stands.
574    #[must_use]
575    pub fn alignment(&self, print_id: PrintId) -> PrintAlignment {
576        self.alignments.print_alignment(print_id)
577    }
578
579    /// The image one print's last check was shown; nothing before its first.
580    #[must_use]
581    pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
582        self.alignments.last_check_image(print_id)
583    }
584
585    /// The whole frame, with the line saying why.
586    fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
587        Ok(ShownImage {
588            fallback: Some(ImageFallback {
589                code: reason.code(),
590                message: reason.to_string(),
591            }),
592            ..ShownImage::plain(
593                self.whole.check_image(None, frame)?,
594                Some(whole_frame_note(reason)),
595            )
596        })
597    }
598
599    /// Keep the camera check a print started under, from its record, so its
600    /// checks are drawn through it from now on.
601    pub fn adopt_camera_check(
602        &self,
603        print_id: PrintId,
604        record: Option<&printobserver_types::EventRecord>,
605    ) {
606        if let Some(record) = record {
607            self.alignments.adopt_camera_check(print_id, record);
608        }
609    }
610
611    /// Judge one frame of a print — its view, and its first-layer alignment
612    /// as `alignment` asks — keeping what that decides. Nothing when no
613    /// calibration or no camera stream is configured, which leaves nothing to
614    /// judge a frame against.
615    #[must_use]
616    pub fn judge_frame(
617        &self,
618        print_id: PrintId,
619        frame: &[u8],
620        frame_sha256: &str,
621        plan: Option<&PlanPosition>,
622        alignment: AlignmentJudging,
623    ) -> Option<Judged> {
624        self.alignments.calibration()?;
625        let url = self.camera_snapshot_url.as_deref()?;
626        Some(self.alignments.judge(
627            print_id,
628            &Judging {
629                frame_jpeg: frame,
630                frame_sha256,
631                camera_snapshot_url: url,
632                plan,
633                alignment,
634            },
635        ))
636    }
637
638    /// The image one frame of a print is shown once it has been judged: the
639    /// three-panel image where the judgement allows it, and the whole frame
640    /// with the reason otherwise.
641    ///
642    /// # Errors
643    ///
644    /// Why no image could be made at all: the frame unreadable, or the image
645    /// unwritable.
646    pub fn image_of(
647        &self,
648        print_id: PrintId,
649        shown: &Shown<'_>,
650        judged: Option<&Judged>,
651    ) -> Result<ShownImage, String> {
652        let previous = self.alignments.previous_check(print_id);
653        match self.chosen(print_id, shown, judged, previous.as_ref())? {
654            Ok(composite) => Ok(composite),
655            Err(reason) => self.whole_frame(shown.frame, &reason),
656        }
657    }
658
659    /// The three-panel image of one judged frame of a print, or why it is
660    /// shown the whole frame instead.
661    fn chosen(
662        &self,
663        print_id: PrintId,
664        shown: &Shown<'_>,
665        judged: Option<&Judged>,
666        previous: Option<&PreviousCheck>,
667    ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
668        let Some(calibration) = self.alignments.calibration() else {
669            return Ok(Err(WholeFrameReason::NoCalibration));
670        };
671        let Some(url) = self.camera_snapshot_url.as_deref() else {
672            return Ok(Err(WholeFrameReason::NoStream));
673        };
674        if shown.paused {
675            return Ok(Err(WholeFrameReason::Paused));
676        }
677        let Some(judged) = judged else {
678            return Ok(Err(WholeFrameReason::AlignmentPending));
679        };
680        if let Some(detail) = &judged.unreadable {
681            return Err(detail.clone());
682        }
683        let Some(plan) = shown.plan else {
684            return Ok(Err(WholeFrameReason::NoPosition));
685        };
686        let at = PlanAt {
687            index: &plan.index,
688            file_position_bytes: plan.file_position_bytes,
689        };
690        if at.index.object_at(at.file_position_bytes).is_none()
691            || at.index.object_outlines().is_empty()
692        {
693            return Ok(Err(WholeFrameReason::NoObject));
694        }
695        if at.index.layer_at(at.file_position_bytes).is_none() {
696            return Ok(Err(WholeFrameReason::NoLayer));
697        }
698        if let Err(reason) = refusal_of(judged) {
699            return Ok(Err(reason));
700        }
701        let current = std::fs::read(shown.frame)
702            .map_err(|error| format!("{} is unreadable: {error}", shown.frame.display()))?;
703        // A previous frame gone from the store, or one that no longer decodes,
704        // is one the panel cannot show, which leaves panel 3 empty rather than
705        // the check without an image.
706        let earlier = previous.and_then(|check| {
707            std::fs::read(&check.frame)
708                .ok()
709                .filter(|bytes| whole_frame(bytes).is_ok())
710                .map(|bytes| (bytes, check.captured_at))
711        });
712        let composed = match compose_at(
713            at,
714            (&current, shown.captured_at),
715            earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
716            url,
717            calibration,
718            judged.correction.as_ref(),
719        ) {
720            Ok(composed) => composed,
721            // The current frame was judged whole by the vision port before it
722            // was stored, and the previous one was decoded above, so neither
723            // refusal is reached by a frame the camera gave; one that is is a
724            // check shown the stored frame, as any check image that cannot be
725            // made is, which `a check image that cannot be written` proves.
726            Err(WholeFrameReason::Refused(
727                ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
728            )) => return Err(detail),
729            Err(reason) => return Ok(Err(reason)),
730        };
731        let destination = self.composite_destination(shown.frame, previous);
732        write_image(&self.whole.directory, &destination, &composed.jpeg)?;
733        let mut note = composite_note(
734            shown.made_for,
735            shown.captured_at,
736            earlier.as_ref().map(|(_, at)| *at),
737        );
738        if shown.made_for == ImageUse::Check
739            && let Some(clause) = self.growth_clause(print_id, plan, &current, url, calibration)
740        {
741            note.push_str(&clause);
742        }
743        Ok(Ok(ShownImage {
744            composite: true,
745            ..ShownImage::plain(destination, Some(note))
746        }))
747    }
748
749    /// What a check's line adds of whether the parts grew: the
750    /// [`not_grown_note`] when the measurement against the newest earlier
751    /// check's frame at least [`MIN_RISE_MM`] below finds they did not, and
752    /// nothing otherwise — no such frame, one gone from the store, a layer
753    /// laying supports alone, or a measurement that found growth or could not
754    /// tell. Each measurement made is said on the log.
755    fn growth_clause(
756        &self,
757        print_id: PrintId,
758        plan: &PlanPosition,
759        current: &[u8],
760        url: &str,
761        calibration: &CameraCalibration,
762    ) -> Option<String> {
763        let layer = plan.index.layer_at(plan.file_position_bytes)?;
764        let print_z_mm = plan.index.layer_z_mm(layer)?;
765        let reference = self
766            .alignments
767            .growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
768        let earlier = std::fs::read(&reference.frame).ok()?;
769        let toolpath = plan.index.layer_toolpath(layer).ok()?;
770        let measured = measure_growth(&GrowthInputs {
771            earlier_jpeg: &earlier,
772            earlier_print_z_mm: reference.print_z_mm,
773            current_jpeg: current,
774            current_print_z_mm: print_z_mm,
775            camera_snapshot_url: url,
776            toolpath: &toolpath,
777            calibration,
778        })
779        .ok()??;
780        let not_grown = measured.not_grown();
781        eprintln!(
782            "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: {}",
783            reference.print_z_mm,
784            reference.captured_at,
785            measured.carried,
786            measured.held,
787            measured.carried_share * 100.0,
788            measured.samples,
789            measured.separation_px,
790            if not_grown { "not grown" } else { "no verdict" }
791        );
792        not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
793    }
794
795    /// Where the three-panel image of one stored frame, after one previous
796    /// check, is written: named for both, which name it uniquely.
797    fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
798        let named = |frame: &Path| {
799            let part = |part: Option<&std::ffi::OsStr>| {
800                part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
801            };
802            format!(
803                "{}-{}",
804                part(frame.parent().and_then(Path::file_name)),
805                part(frame.file_name())
806            )
807        };
808        let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
809        self.whole
810            .directory
811            .join(format!("{}-composite-after-{after}.jpg", named(frame)))
812    }
813}
814
815impl CheckImages for PanelImages {
816    fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
817        self.whole.check_image(print_id, frame)
818    }
819
820    fn restart_growth(&self, print_id: PrintId) {
821        self.alignments.restart_growth(print_id);
822    }
823
824    fn composes(&self, print_id: PrintId) -> bool {
825        self.alignments.calibration().is_some()
826            && self.camera_snapshot_url.is_some()
827            && (self.alignments.started_under_a_camera_check(print_id)
828                || matches!(
829                    self.alignments.print_alignment(print_id),
830                    PrintAlignment::Passed { .. }
831                ))
832    }
833
834    fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
835        let Some(print_id) = request.print_id else {
836            return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
837        };
838        if let Some(record) = &request.camera_check {
839            self.alignments.adopt_camera_check(print_id, record);
840        }
841        // A check taken while the printer reports the print paused is not
842        // judged: its bed is lowered off the plan's height.
843        let judged = if request.paused {
844            None
845        } else {
846            let alignment = if request.made_for == ImageUse::Check && request.own_camera {
847                AlignmentJudging::WhilePending
848            } else {
849                AlignmentJudging::Never
850            };
851            match std::fs::read(request.frame) {
852                Ok(current) => self.judge_frame(
853                    print_id,
854                    &current,
855                    request.frame_sha256,
856                    request.plan.as_ref(),
857                    alignment,
858                ),
859                Err(error) => {
860                    return Err(format!(
861                        "{} is unreadable: {error}",
862                        request.frame.display()
863                    ));
864                }
865            }
866        };
867        let shown = Shown {
868            frame: request.frame,
869            captured_at: request.captured_at,
870            made_for: request.made_for,
871            plan: request.plan.as_ref(),
872            paused: request.paused,
873        };
874        let mut image = self.image_of(print_id, &shown, judged.as_ref())?;
875        image.records = judged.map(|judged| judged.records).unwrap_or_default();
876        // Only the camera's own frame is a later check's panel 3 or the
877        // reference its growth is measured from: a detector's picture need be
878        // neither the calibration's size nor its stream, and the composer
879        // refuses a previous frame of another size than the current one.
880        if request.made_for == ImageUse::Check && request.own_camera {
881            self.alignments.record_check(
882                print_id,
883                &PreviousCheck {
884                    frame: request.frame.to_path_buf(),
885                    captured_at: request.captured_at,
886                },
887            );
888            if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
889                self.alignments.record_checked_frame(
890                    print_id,
891                    CheckedFrame {
892                        frame: request.frame.to_path_buf(),
893                        captured_at: request.captured_at,
894                        print_z_mm,
895                    },
896                    MIN_RISE_MM,
897                );
898            }
899        }
900        if request.made_for == ImageUse::Check {
901            image.records.extend(self.alignments.note_check_image(
902                print_id,
903                LastCheckImage {
904                    at: request.captured_at,
905                    kind: image.kind(),
906                    fallback: image.fallback.clone(),
907                },
908                request.frame_sha256,
909            ));
910        }
911        Ok(image)
912    }
913}