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/// What a check's note says of the drawing before it says what a part off it
192/// means: an agent shown a part off its walls otherwise explains the
193/// difference as the camera or the bed having shifted in view.
194const CAMERA_HOLDS: &str = "the camera does not shift in regular operation and the drawing already accounts for the bed's travel, so ";
195
196/// The line saying a check or a look was shown the three-panel image of the
197/// frame captured at `current_at`, beside the frame `previous_at` names: panel
198/// 3 empty when no earlier check's frame is at hand — the print's first check,
199/// or one whose earlier frame is gone from the store.
200///
201/// A check's names which frame each panel is and when each was captured, and
202/// says what the skill says: the camera does not shift and the drawing follows
203/// the bed, so a part off it has moved unless there is strong evidence
204/// otherwise, and no later frame undoes it. A turn handed a check's image decides on it, with no look to
205/// stall on, so this is what it decides from. A look's says only what each
206/// panel is.
207#[must_use]
208pub fn composite_note(
209    made_for: ImageUse,
210    current_at: Timestamp,
211    previous_at: Option<Timestamp>,
212) -> String {
213    let (current, previous, moved) = match (made_for, previous_at) {
214        (ImageUse::Look, at) => (
215            "this layer's planned toolpath drawn on the frame".to_owned(),
216            if at.is_none() {
217                "panel 3 empty, no earlier check's frame being at hand".to_owned()
218            } else {
219                "panel 3 the previous check's frame".to_owned()
220            },
221            String::new(),
222        ),
223        (ImageUse::Check, None) => (
224            format!(
225                "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
226            ),
227            "panel 3 empty, no earlier check's frame being at hand".to_owned(),
228            format!(
229                "; {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"
230            ),
231        ),
232        (ImageUse::Check, Some(at)) => (
233            format!(
234                "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
235            ),
236            format!("panel 3 the previous check's frame, captured {at}"),
237            format!(
238                "; {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"
239            ),
240        ),
241    };
242    format!(
243        "{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part being printed, {previous}{moved}",
244        printobserver_panels::compose::PANEL_WIDTH,
245        printobserver_panels::compose::IMAGE_HEIGHT
246    )
247}
248
249/// What a check image is composed from, beyond the frames: the print's plan at
250/// one file position.
251#[derive(Debug, Clone, Copy)]
252pub struct PlanAt<'a> {
253    /// The print's G-code index, its toolpaths read from its spool.
254    pub index: &'a GcodeIndex,
255    /// The check's file position.
256    pub file_position_bytes: u64,
257}
258
259/// Compose the three-panel check image of one frame at one file position, as
260/// every check of a print whose alignment passed is shown it: the active
261/// object at that position, the layer there — and, when that layer lays
262/// supports alone, the nearest object layer below it — over the frame, with
263/// `previous` as panel 3.
264///
265/// # Errors
266///
267/// [`WholeFrameReason`] naming what the index lacks at that position, or the
268/// composer's own refusal.
269pub fn compose_at(
270    plan: PlanAt<'_>,
271    current: (&[u8], Timestamp),
272    previous: Option<(&[u8], Timestamp)>,
273    camera_snapshot_url: &str,
274    calibration: &CameraCalibration,
275) -> Result<CheckImage, WholeFrameReason> {
276    let index = plan.index;
277    let position = plan.file_position_bytes;
278    let active_object = index
279        .object_at(position)
280        .filter(|object| *object < index.object_outlines().len())
281        .ok_or(WholeFrameReason::NoObject)?;
282    let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
283    let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
284    let unread =
285        |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
286    let toolpath = index.layer_toolpath(layer).map_err(unread)?;
287    let below = if toolpath.carries_object_extrusion() {
288        None
289    } else {
290        index
291            .object_layer_at_or_below(layer)
292            .map(|below| index.layer_toolpath(below))
293            .transpose()
294            .map_err(unread)?
295    };
296    compose_check_image(&CheckImageInputs {
297        current_jpeg: current.0,
298        current_at: current.1,
299        camera_snapshot_url,
300        previous,
301        outlines: index.object_outlines(),
302        active_object,
303        toolpath: &toolpath,
304        object_layer_below: below.as_ref(),
305        print_z_mm,
306        calibration,
307    })
308    .map_err(WholeFrameReason::Refused)
309}
310
311/// Every check's image, the three-panel one where it can be trusted and the
312/// whole frame otherwise, each with the line saying which and why.
313pub struct PanelImages {
314    /// The whole frames, and where every image is written.
315    whole: WholeFrames,
316    /// Each print's alignment verdict and last check, and the calibration.
317    alignments: Arc<Alignments>,
318    /// The configured camera's snapshot address: the stream every frame of a
319    /// print is of, an alert's included, which the camera's own feed relays.
320    camera_snapshot_url: Option<String>,
321}
322
323impl core::fmt::Debug for PanelImages {
324    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
325        formatter
326            .debug_struct("PanelImages")
327            .field("whole", &self.whole)
328            .field("camera_snapshot_url", &self.camera_snapshot_url)
329            .finish_non_exhaustive()
330    }
331}
332
333impl PanelImages {
334    /// The images of one state directory's frames.
335    #[must_use]
336    pub fn new(
337        state_dir: &Path,
338        alignments: Arc<Alignments>,
339        camera_snapshot_url: Option<String>,
340    ) -> Self {
341        Self {
342            whole: WholeFrames::under(state_dir),
343            alignments,
344            camera_snapshot_url,
345        }
346    }
347
348    /// The whole frame, with the line saying why.
349    fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
350        Ok(ShownImage {
351            path: self.whole.check_image(None, frame)?,
352            note: Some(whole_frame_note(reason)),
353            composite: false,
354        })
355    }
356
357    /// The three-panel image of one request of a print, or why it is shown
358    /// the whole frame instead.
359    fn composite(
360        &self,
361        print_id: PrintId,
362        request: &CheckImageRequest<'_>,
363        previous: Option<&PreviousCheck>,
364    ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
365        let Some(calibration) = self.alignments.calibration() else {
366            return Ok(Err(WholeFrameReason::NoCalibration));
367        };
368        let Some(url) = self.camera_snapshot_url.as_deref() else {
369            return Ok(Err(WholeFrameReason::NoStream));
370        };
371        let Some(plan) = &request.plan else {
372            return Ok(Err(WholeFrameReason::NoPosition));
373        };
374        let at = PlanAt {
375            index: &plan.index,
376            file_position_bytes: plan.file_position_bytes,
377        };
378        if at.index.object_at(at.file_position_bytes).is_none()
379            || at.index.object_outlines().is_empty()
380        {
381            return Ok(Err(WholeFrameReason::NoObject));
382        }
383        if at.index.layer_at(at.file_position_bytes).is_none() {
384            return Ok(Err(WholeFrameReason::NoLayer));
385        }
386        match self.alignments.print_alignment(print_id) {
387            PrintAlignment::Passed { .. } => {}
388            PrintAlignment::Pending => return Ok(Err(WholeFrameReason::AlignmentPending)),
389            PrintAlignment::Unavailable => {
390                return Ok(Err(WholeFrameReason::AlignmentUnavailable));
391            }
392            PrintAlignment::Failed { reason } => {
393                return Ok(Err(WholeFrameReason::AlignmentFailed(reason)));
394            }
395        }
396        let current = std::fs::read(request.frame)
397            .map_err(|error| format!("{} is unreadable: {error}", request.frame.display()))?;
398        // A previous frame gone from the store, or one that no longer decodes,
399        // is one the panel cannot show, which leaves panel 3 empty rather than
400        // the check without an image.
401        let earlier = previous.and_then(|check| {
402            std::fs::read(&check.frame)
403                .ok()
404                .filter(|bytes| whole_frame(bytes).is_ok())
405                .map(|bytes| (bytes, check.captured_at))
406        });
407        let composed = match compose_at(
408            at,
409            (&current, request.captured_at),
410            earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
411            url,
412            calibration,
413        ) {
414            Ok(composed) => composed,
415            // The current frame was judged whole by the vision port before it
416            // was stored, and the previous one was decoded above, so neither
417            // refusal is reached by a frame the camera gave; one that is is a
418            // check shown the stored frame, as any check image that cannot be
419            // made is, which `a check image that cannot be written` proves.
420            Err(WholeFrameReason::Refused(
421                ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
422            )) => return Err(detail),
423            Err(reason) => return Ok(Err(reason)),
424        };
425        let destination = self.composite_destination(request.frame, previous);
426        write_image(&self.whole.directory, &destination, &composed.jpeg)?;
427        Ok(Ok(ShownImage {
428            path: destination,
429            note: Some(composite_note(
430                request.made_for,
431                request.captured_at,
432                earlier.as_ref().map(|(_, at)| *at),
433            )),
434            composite: true,
435        }))
436    }
437
438    /// Where the three-panel image of one stored frame, after one previous
439    /// check, is written: named for both, which name it uniquely.
440    fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
441        let named = |frame: &Path| {
442            let part = |part: Option<&std::ffi::OsStr>| {
443                part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
444            };
445            format!(
446                "{}-{}",
447                part(frame.parent().and_then(Path::file_name)),
448                part(frame.file_name())
449            )
450        };
451        let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
452        self.whole
453            .directory
454            .join(format!("{}-composite-after-{after}.jpg", named(frame)))
455    }
456}
457
458impl CheckImages for PanelImages {
459    fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
460        self.whole.check_image(print_id, frame)
461    }
462
463    fn composes(&self, print_id: PrintId) -> bool {
464        self.alignments.calibration().is_some()
465            && self.camera_snapshot_url.is_some()
466            && matches!(
467                self.alignments.print_alignment(print_id),
468                PrintAlignment::Passed { .. }
469            )
470    }
471
472    fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
473        let Some(print_id) = request.print_id else {
474            return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
475        };
476        let previous = self.alignments.previous_check(print_id);
477        let shown = match self.composite(print_id, request, previous.as_ref())? {
478            Ok(composite) => composite,
479            Err(reason) => self.whole_frame(request.frame, &reason)?,
480        };
481        if request.made_for == ImageUse::Check {
482            self.alignments.record_check(
483                print_id,
484                &PreviousCheck {
485                    frame: request.frame.to_path_buf(),
486                    captured_at: request.captured_at,
487                },
488            );
489        }
490        Ok(shown)
491    }
492}