nkscan 0.11.0

A platform-agnostic, performant driver for Nikon film scanners
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
//! Scanning all the available film at once to generate a thumbnail
//!
//! `Address` byte 16 says whether the unit publishes frames at all, and
//! `Frames` says whether it knows where they end. A fixed-format mount does;
//! loose film reports a length of zero until something measures it.
//!
//! `Features` puts thumbnail in the host cooperation bits on both families, so
//! the unit hands us the pass and expects us to make sense of it.

use super::{framing, pass::Pass, strip, window};
use crate::{
    error::Error,
    protocol::{
        caps::{
            Capabilities,
            set_window::{ColorInterleaving, ScanKind, ScanMode},
        },
        data::{
            Boundary, BoundaryType2, FramePosition, PerfInformation, PerforationInformation, Rect,
        },
        decode::{Image, Samples},
        model::Model,
        window::{Flags, Window},
    },
};
use tracing::*;

/// The pitch of a 135 perforation in ten-thousandths of a millimeter, ISO 1007
const PERFORATION_MM_E4: u64 = 47_498;

/// Ten-thousandths of a millimeter in an inch, to turn that into addresses
const INCH_MM_E4: u64 = 254_000;

/// The least film a measurement needs, in quarter perforations. Below this the
/// quarter that a record is rounded to is a large part of the measurement
const MEASURED_QUARTERS: u64 = 16;

/// Stage addresses one thumbnail column spans
///
/// The optical resolution over the resolution the pass asks for, rounded down,
/// which is the pass's own `line_pitch` computed without the pass
pub(crate) fn line_pitch(caps: &Capabilities) -> u32 {
    let optical =
        u32::from(caps.address.y_axis.optical_dpi).max(u32::from(caps.address.x_axis.optical_dpi));
    match u32::from(caps.address.thumbnail_resolution.start) {
        0 => 1,
        asked => (optical / asked).max(1),
    }
}

/// How far the film moves between two thumbnail lines
///
/// Held as the film measured over the lines it moved in, because the answer is
/// not a whole number of addresses and a frame spans over a hundred lines
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinePitch {
    addresses: u64,
    lines: u64,
}

impl LinePitch {
    /// What the pass asked for, which is [`line_pitch`]
    pub fn computed(caps: &Capabilities) -> Self {
        Self {
            addresses: u64::from(line_pitch(caps)),
            lines: 1,
        }
    }

    /// What the film did, measured off the perforation table
    ///
    /// The film does not keep to the thumbnail resolution the unit reports,
    /// and the error accumulates over a frame. 2-11-8's table is the ruler
    /// that settles it: each record is one line's absolute position in
    /// perforations and quarters of one, and a 135 perforation is 4.7498 mm.
    ///
    /// The count does not run the whole pass. The unit counts nothing before
    /// the first perforation and stops at the last, so this measures between
    /// the first record that moved and the last one that moved. `None` where
    /// the table measures nothing, or gives a pitch the pass could not have
    /// asked for. The caller then keeps the computed pitch
    pub fn measured(caps: &Capabilities, perfs: &PerfInformation) -> Option<Self> {
        let quarters =
            |p: &PerforationInformation| u64::from(p.perf_number) * 4 + u64::from(p.perf_decimal);

        let first = perfs.perfs.first()?;
        let last = perfs.perfs.last()?;
        // Past the flat head, and up to the flat tail
        let head = perfs
            .perfs
            .iter()
            .position(|p| quarters(p) != quarters(first))?;
        let tail = perfs
            .perfs
            .iter()
            .rposition(|p| quarters(p) != quarters(last))?
            + 1;

        let lines = (tail.checked_sub(head)?) as u64;
        let moved =
            quarters(perfs.perfs.get(tail)?).checked_sub(quarters(perfs.perfs.get(head)?))?;
        if lines == 0 || moved < MEASURED_QUARTERS {
            return None;
        }

        let optical = u64::from(
            caps.address
                .y_axis
                .optical_dpi
                .max(caps.address.x_axis.optical_dpi),
        );
        let addresses = moved * optical * PERFORATION_MM_E4 / (4 * INCH_MM_E4);

        let measured = Self { addresses, lines };
        // The pass moved the film once for every line it asked for, so a
        // measurement far from what it asked for is a table this cannot read
        let asked = u64::from(line_pitch(caps));
        let apart = measured.addresses.abs_diff(asked * lines);
        (apart * 4 <= asked * lines).then_some(measured)
    }

    /// Stage addresses one thumbnail column spans, as a fraction
    ///
    /// Held as a ratio internally. This is for a caller that maps between
    /// thumbnail columns and feed addresses itself
    pub fn addresses_per_column(&self) -> f64 {
        self.addresses as f64 / self.lines.max(1) as f64
    }

    /// The Y address of a thumbnail line
    pub fn address_of(&self, line: u32) -> u32 {
        (u64::from(line) * self.addresses / self.lines.max(1)) as u32
    }

    /// How many thumbnail lines a length of film spans
    ///
    /// A length rather than a position, so the axis origin does not come into
    /// it the way it does for [`Self::line_at`]
    pub fn columns(&self, addresses: u32) -> usize {
        let per = self.addresses.max(1);
        ((u64::from(addresses) * self.lines + per / 2) / per) as usize
    }

    /// The thumbnail line nearest a Y address
    pub fn line_at(&self, caps: &Capabilities, y: u32) -> usize {
        let origin = caps.address.y_axis.address_range.start;
        let film = u64::from(y.saturating_sub(origin)) * self.lines.max(1);
        let addresses = self.addresses.max(1);
        ((film + addresses / 2) / addresses) as usize
    }
}

/// The top of a frame of `format` centered on the middle of its picture
///
/// The format is the rectangle the caller scans. A camera gate is not that
/// rectangle, so the format is put over the middle of the picture and the
/// difference goes to both ends. `None` where the axis is shorter than the
/// format
fn top_of(caps: &Capabilities, middle: u32, format: u32) -> Option<u32> {
    let origin = caps.address.y_axis.address_range.start;
    let end = caps.address.y_axis.address_range.last;
    let last = end.checked_sub(format)?;
    Some(
        middle
            .saturating_sub(format / 2)
            .clamp(origin.min(last), last),
    )
}

/// Whether this unit and adapter will thumbnail at all
///
/// Support follows the adapter rather than the model, so this is re-decided
/// whenever the adapter changes
pub fn available(caps: &Capabilities) -> bool {
    caps.set_window.kind.contains(ScanKind::THUMBNAIL)
        && caps.address.thumbnail_resolution.start > 0
}

/// The top of each frame the pass holds, in Y addresses
///
/// The two frame tables measure the same film and differ only in the pitch. A
/// unit with a perforation table measures the pitch. A unit without one
/// computes the pitch. `None` where the strip holds no frame
fn tops(
    caps: &Capabilities,
    image: &Image,
    pitch: LinePitch,
    format: u32,
) -> Option<(Vec<u32>, strip::Strip)> {
    let found = strip::find(image, pitch.columns(format))?;
    let origin = caps.address.y_axis.address_range.start;
    let tops = found
        .frames
        .iter()
        .map(|frame| origin + pitch.address_of((frame.start + frame.len() / 2) as u32))
        .filter_map(|middle| top_of(caps, middle, format))
        .collect();
    Some((tops, found))
}

/// The frame table a thumbnail measures, 2-11-6
///
/// `length` is the frame's extent along the feed, the film format, which
/// nothing advertises. Every rectangle comes out that long: the captures'
/// measured tables move the tops about and leave the heights at the format.
///
/// Also answers the pitch the rectangles were placed with, so a caller can put
/// a rectangle drawn on the thumbnail onto the film
pub fn frames(
    caps: &Capabilities,
    pass: &Pass,
    samples: &Samples,
    length: u32,
) -> Result<(Boundary, LinePitch), Error> {
    let format = window::reachable_blocks(caps, length);
    framing::reachable(caps, format)?;
    let image = Image::new(&pass.layout, samples)?;

    // This mechanism has no perforation table to measure the film against, so
    // the pitch is the one the pass asked for
    let pitch = LinePitch {
        addresses: u64::from(pass.layout.line_pitch.max(1)),
        lines: 1,
    };
    let (left, width) = opening(caps);

    let Some((tops, found)) = tops(caps, &image, pitch, format) else {
        info!("nothing on the strip to frame");
        return Ok((Boundary::default(), pitch));
    };

    // The window addresses the film here, so the rectangle is the frame
    let frames: Vec<Rect> = tops
        .into_iter()
        .map(|top| Rect {
            top,
            left,
            bottom: top + format,
            right: left + width,
        })
        .collect();

    info!(
        frames = frames.len(),
        pitch = pitch.address_of(found.pitch as u32),
        contrast = found.contrast,
        "measured the loaded strip"
    );
    for (n, rect) in frames.iter().enumerate() {
        debug!(frame = n + 1, ?rect, "frame rect");
    }
    Ok((Boundary { frames }, pitch))
}

pub fn frames_type2(
    caps: &Capabilities,
    pass: &Pass,
    samples: &Samples,
    perf_info: &PerfInformation,
    length: u32,
) -> Result<(BoundaryType2, u32, LinePitch), Error> {
    // Whole readout blocks, and trimmed rather than refused where the format
    // is taller than the axis reaches
    let format = window::reachable_blocks(caps, length);
    framing::reachable(caps, format)?;

    let image = Image::new(&pass.layout, samples)?;

    // A thumbnail column is one line pitch of film, and the pass starts where
    // the Y axis does, so a column is an address. The film does not keep to
    // the pitch the pass asked for, and the table the unit just measured says
    // what it did keep to
    let pitch = match LinePitch::measured(caps, perf_info) {
        Some(measured) => {
            debug!(
                per_thousand_lines = measured.address_of(1000),
                "measured the thumbnail line against the perforation table"
            );
            measured
        }
        None => {
            debug!("no perforation table to measure the thumbnail line against");
            LinePitch::computed(caps)
        }
    };
    let Some((tops, found)) = tops(caps, &image, pitch, format) else {
        info!("nothing on the strip to frame");
        return Ok((BoundaryType2::default(), format, pitch));
    };

    // The table commonly falls short of the pass: the unit stops counting
    // perforations past the last one on the strip. That is not a fault on its
    // own, but a frame whose column falls past the end has no record to
    // register it with and drops below
    if perf_info.perfs.len() != image.cols {
        debug!(
            perfs = perf_info.perfs.len(),
            columns = image.cols,
            "the perforation table does not run the length of the thumbnail pass"
        );
    }

    // 2-11-9 moves the film so that an entry's top address is the first line
    // the pass reads, and the record is how it gets there. The two are one
    // reading of one place and move together
    let frames: Vec<FramePosition> = tops
        .into_iter()
        .filter_map(|top| {
            let col = pitch.line_at(caps, top);
            let perf = perf_info.at(col);
            debug!(col, top, ?perf, "the pass over a frame");
            match perf {
                Some(perf) => Some(FramePosition::new(top, perf)),
                None => {
                    // Past wherever the perforation table stopped: nothing to
                    // register this frame's stage position against
                    warn!(col, top, "no perforation reading for this frame, dropped");
                    None
                }
            }
        })
        .collect();

    info!(
        frames = frames.len(),
        pitch = pitch.address_of(found.pitch as u32),
        contrast = found.contrast,
        "measured the loaded strip"
    );
    for (n, frame) in frames.iter().enumerate() {
        debug!(frame = n + 1, ?frame, "frame position");
    }

    Ok((BoundaryType2 { frames }, format, pitch))
}

/// Where the adapter's opening sits on the sensor, and how wide it is
///
/// The first published image is the opening: a frame narrower than that is a
/// crop, and cropping is not what a pass over the whole strip is for
fn opening(caps: &Capabilities) -> (u32, u32) {
    let x = &caps.address.x_axis;
    match caps.frames.as_ref().and_then(|f| f.images.first()) {
        Some(opening) => (opening.left, opening.width),
        None => (x.address_range.start, x.boundary),
    }
}

/// Windows over everything the adapter can reach, one per channel
pub(crate) fn windows(caps: &Capabilities) -> Result<Vec<Window>, Error> {
    let y = &caps.address.y_axis;
    let unsupported = |reason: String| Error::Unsupported {
        op: "thumbnail window",
        reason,
    };

    // Line ordering owes the host nothing, where the three-line mode owes it
    // registration. Take it when offered rather than assuming it is
    let offered = caps.set_window.interleaving;
    if !offered.contains(ColorInterleaving::LINE_WITHOUT_DISTANCE) {
        return Err(unsupported(format!(
            "a thumbnail needs line ordering and this unit offers {offered:?}"
        )));
    }

    let flags = match caps.identity.model() {
        Some(Model::Ls8000 | Model::Ls9000) => Flags::empty(),
        Some(_) => Flags::POSITIVE | Flags::AVERAGING,
        None => {
            return Err(Error::Unsupported {
                op: "thumbnail window",
                reason: "unrecognized model".into(),
            });
        }
    };

    let (left, width) = opening(caps);
    let mut windows = window::blank(caps, &window::color_channels(caps))?;
    for w in &mut windows {
        w.resolution = (
            caps.address.thumbnail_resolution.start,
            caps.address.thumbnail_resolution.start,
        );
        // Y starts at the axis rather than the first frame, so the leading
        // edge of the film is in the pass and can be found
        w.origin = (left, y.address_range.start);
        w.size = (width, y.address_range.last);
        w.scanning_kind = ScanKind::THUMBNAIL;
        w.scanning_mode = ScanMode::NORMAL_QUALITY;
        w.flags = flags;
        w.color_interleaving = ColorInterleaving::LINE_WITHOUT_DISTANCE;
    }
    Ok(windows)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scan::window::tests::caps;

    /// A table like the one an LS-50 measures: a flat head with nothing
    /// counted yet, then `perforations` of film at `lines` thumbnail lines
    /// each, then a flat tail past the last perforation
    fn table(head: usize, lines: usize, perforations: usize, tail: usize) -> PerfInformation {
        let mut perfs = vec![PerforationInformation::default(); head];
        for line in 0..lines * perforations {
            let quarters = line * 4 / lines.max(1);
            perfs.push(PerforationInformation {
                perf_number: (quarters / 4) as u16,
                perf_decimal: (quarters % 4) as u8,
                ..Default::default()
            });
        }
        let last = perfs.last().cloned().unwrap_or_default();
        perfs.extend(std::iter::repeat_n(last, tail));
        PerfInformation { perfs }
    }

    /// 4.7498 mm a perforation over a 4000 dpi axis is 748 addresses, so a
    /// quarter every 4.5 lines is 41.6 addresses a line: the film's own pitch,
    /// not the 41 that 4000/97 computes
    #[test]
    fn the_perforation_table_measures_the_line() {
        let mut caps = caps();
        caps.address.thumbnail_resolution = (97u16..=97u16).into();
        assert_eq!(line_pitch(&caps), 41);

        // A perforation every 18 lines, 40 of them
        let measured = LinePitch::measured(&caps, &table(20, 18, 40, 30)).expect("a pitch");

        // 748 addresses of film every 18 lines, so 41.555 a line
        assert_eq!(measured.address_of(1000), 41_555);
        // A 135 frame is about 137 lines, where the computed pitch is a
        // millimeter short over the frame
        assert_eq!(
            measured.address_of(137) - LinePitch::computed(&caps).address_of(137),
            76
        );
        assert_eq!(measured.line_at(&caps, measured.address_of(137)), 137);
    }

    /// Nothing to measure against, or a table that says something the pass
    /// cannot have done, and the computed pitch stands
    #[test]
    fn an_unmeasurable_table_keeps_the_computed_pitch() {
        let mut caps = caps();
        caps.address.thumbnail_resolution = (97u16..=97u16).into();

        assert_eq!(
            LinePitch::measured(&caps, &PerfInformation::default()),
            None
        );
        // Flat: the unit counted nothing
        assert_eq!(LinePitch::measured(&caps, &table(40, 1, 0, 0)), None);
        // Three perforations is not enough film to divide by
        assert_eq!(LinePitch::measured(&caps, &table(10, 18, 3, 10)), None);
        // A perforation every other line is ten times what the pass asked for
        assert_eq!(LinePitch::measured(&caps, &table(10, 2, 40, 10)), None);
    }
}