mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 01:44:25 +00:00
+10








8d3f245d2a
* craft-metadata: EXIF, IPTC-IIM, XMP and GPX from LightCraft lightcraft-meta at 5b61ce1e, as one crate with a module per format: exif (read, write, maker-note lens, focus point, tag listing), iptc, xmp (parse, write, merge), gpx, and the JPEG, PNG, WebP, TIFF, RAF and CR3 containers. They share Metadata, DateTime, Gps and Orientation. Changed in the move: - TIFF comes from craft-tiff; Point, Rect and Orientation are the crate's own. - The app namespace is a parameter: parse_xmp_with, write_xmp_with and MergeRules::namespaces take it, and XmpData no longer has lc_settings. - The HEIF, PSD and MRW readers stay out, since craft-heif, craft-psd and craft-raw read those containers; from_embedded takes the blocks they find. * craft-metadata: a RW2 reads ISO and the rest of its Exif from the JpgFromRaw A RW2's own Exif IFD is a short subset. What it lacks is filled from the Exif of the embedded JpgFromRaw, then from the ISO tags of the Panasonic IFD0 (0x0017, 0x0037), each only in its recorded field type. 65535 in a SHORT ISOSpeedRatings is the overflow marker and states no ISO. The private tags are read only in a RW2 stream, under the caller's parse options. Ported from storytold/lightcraft#3518. * craft-metadata: the Exif rating is written, and 65535 reads as rejected write_exif writes Rating (0x4746), with 0xFFFF for a rejected photo, and from_tiff reads 65535 as -1 instead of clamping it to 5. Ported from storytold/lightcraft#1995. * craft-metadata: one shutter-speed formatter, exact to four digits format_exposure_time shows a duration within 0.1% of 1/n second as 1/n and anything else to four significant digits, so 0.3 s, 1/2.8 s and 0.625 s are no longer rounded to a reciprocal or one decimal. Metadata::exposure_display and the ExposureTime tag row both use it. Ported from storytold/lightcraft#1692. * craft-metadata: JPEG XL containers give their Exif and xml boxes The first Exif and xml box of a JPEG XL container, plain or Brotli-wrapped in brob, honouring the Exif box's TIFF header offset. A brob payload is capped at 32 MiB. A bare codestream has no metadata. Ported from storytold/lightcraft#3756. * craft-metadata: XMP Resource structs flatten their attribute fields A property with rdf:parseType="Resource" may give its fields as attributes as well as child elements. Only the children were flattened into XmpData::properties; the attributes now are too, as for a nested rdf:Description. Ported from storytold/lightcraft#1226 (the XMP part). * craft-metadata: a capture date of just a year or a month stays as stated XMP dates may stop at the year (1983) or the month (1983-04). DateTime now has a DatePrecision; such a date writes back to XMP as stated and only in photoshop:DateCreated, and write_exif leaves it out, since an Exif date cannot say it. Ported from storytold/lightcraft#3502. * craft-metadata: Fujifilm in-camera recipes from the maker note fuji module: the film simulation and the rest of the in-camera recipe (grain, colour chrome, tone, dynamic range, white balance and its shift, sharpness, noise reduction, clarity) from a Fujifilm maker note. recipe_from_exif, recipe_from_bytes (TIFF, JPEG, RAF) and read_recipe_file, which reads only as far as the metadata. from_embedded fills Metadata::fuji_recipe and file_tag_rows lists the recipe under Fujifilm. Ported from storytold/lightcraft#1209. * craft-metadata: the linear-time scan test compares times, not a fixed bound The test asserted that 200 000 attributes scan in under 5 s, which failed on a loaded machine. It now scans 25 000 and 100 000 attributes, takes the best of three runs of each, and asserts that four times the attributes take less than ten times as long. Linear scans give about 4; a quadratic duplicate check gave 18.6 and fails. * craft-metadata: interleave the linear-time scan test's runs The best-of-three ratio still failed once under load. The test now alternates five runs of 50 000 and 200 000 attributes and compares the fastest of each, so a burst of load slows both sizes. Six runs at load average 55 gave ratios of 3.9 to 5.4 against the bound of 10. * craft-metadata: XmpData::toolkit, the x:xmptk of the packet The name of the program that wrote a packet, from x:xmptk on x:xmpmeta (or x:xaptk on the older x:xapmeta), whatever prefix the packet binds to adobe:ns:meta/. write_xmp_with writes XmpWrite::toolkit there, and the test reads it back, escaped characters included. * craft-metadata: mpf, the Multi-Picture index of a JPEG mpf::images lists the images an APP2 MPF index (CIPA DC-007) puts after the primary image, with their file offsets; the index is read with craft-tiff, in either byte order, up to 16 entries. mpf::write inserts an index after the primary's leading APPn segments and appends the other images, with the primary listed as the representative baseline image: the layout LightCraft's gain map JPEG writer uses, for any number of images. mpf::markers lists the marker segments before the first scan, for APPn payloads such as ISO 21496-1 gain map metadata. * craft-metadata: edit, byte-preserving Exif and XMP edits from PhotoCraft PhotoCraft's orientation, resolution and Exif colour-space code (codecs orientation.rs without the pixel transforms, resolution.rs, exif_color.rs), at photocraft f1b5e7d72, as the edit module: - upright_exif and upright_xmp set Orientation to 1 in place, in the entry's own type and width, every well-formed duplicate included. - exif_with_resolution and xmp_with_resolution set the resolution in place and remove entries that cannot be rewritten; the _adding_missing variant appends a new IFD0 when there are none. - export_exif and export_xmp do both and drop the source Exif thumbnail, with the overlap scan bounded. - exif_orientation, exif_resolution, xmp_resolution, photoshop_resolution, exif_color_space and resolution read the same values with the editors' rules (first entry wins, SHORT or LONG only, BigTIFF accepted). The tests that call these functions directly move with them (the codec round trips stay in PhotoCraft): the orientation, resolution, thumbnail and compaction tests, the comparison-counting complexity test and the colour space tests. * craft-metadata: exif_with_pixel_size, the written size in PixelX/YDimension A camera records its sensor's size in the Exif IFD's PixelXDimension and PixelYDimension, which after a crop, resize or rotation names a size the exported file does not have. exif_with_pixel_size rewrites each one that holds one SHORT or LONG, in place and as a LONG, in classic and BigTIFF blocks, with the JPEG Exif prefix kept. Ported from storytold/photocraft#12407 (the format part). * craft-metadata: an ISO 8601 clock needs two-digit hours and minutes Ported from storytold/lightcraft#3523. * craft-metadata: a UTC offset needs a two-digit minute field Ported from storytold/lightcraft#3467. * craft-metadata: tiff:Orientation is read only as an integral code 1 to 8 A fractional or out-of-range value stays a raw property and does not become the photo's orientation. Ported from storytold/lightcraft#3495. * craft-metadata: an XMP ISO is read only when it is a whole number in range A fractional, non-positive or out-of-range ISO is not truncated or saturated into one; the next candidate property is tried instead. Ported from storytold/lightcraft#3633. * craft-metadata: XMP pixel dimensions are read only as exact whole numbers A malformed, fractional, negative or out-of-range tiff:ImageWidth or ImageLength is no longer truncated or saturated, and lets the exif:Pixel dimension take its place. Numbers are compared as exact decimal digits, so wide rationals stay exact. The ISO reader now uses the same exact reader (both PRs added one). Ported from storytold/lightcraft#3690. * craft-metadata: XMP GPS minutes and seconds must be under 60; tell when a read was cut short A coordinate such as 45,60N is no longer normalised to a plausible point; the raw property stays. XmpData::properties_truncated says the flattened property map ran past its key budget, Embedded::chunk_walk_incomplete says a PNG or WebP chunk walk stopped early, and jpeg_segments_with_all_xmp returns every ordinary XMP packet of a JPEG, so a caller that must prove a file carries no location can refuse what it could not inspect. Ported from storytold/lightcraft#3054. * craft-metadata: IPTC Time Created counts only when it is a whole, valid time A date with a six-digit clock and no zone stays date-only; HHMMSS±HHMM carries an offset; clocks and offsets are range-checked. A partial offset, extra digits, a leap second or trailing text no longer becomes a capture time, so it cannot block valid XMP or Exif. Ported from storytold/lightcraft#3448. * craft-metadata: test hostile XMP attribute references The one-pass reference scan (entity_end) already covers the bug that storytold/lightcraft#3007 fixed another way; its test is added here and passes on this implementation: unknown, unterminated and far-away references stay verbatim, a value of a million ampersands or of a million zeros is read once, and multi-byte text around a reference stays whole. Test from storytold/lightcraft#3007. * craft-metadata: parse_gps_position; an XMP coordinate's sign comes from its letter parse_gps_position reads an exif:GPSLatitude and GPSLongitude pair and checks both axes. A negative degree, minute or second part, or a letter of the other axis (10,30E as a latitude), is malformed; the letter may be either case. Ported from storytold/lightcraft#2088 (the format part). * craft-metadata: bound the XMP namespace declarations in scope; merge into an empty rdf:RDF Prefix lookup scans every declaration in scope, so one start tag with thousands of xmlns declarations made parsing and merging quadratic. More than 512 declarations in scope is now TooComplex, in parse_xmp and in merge_xmp's scan. merge_xmp also opens a self-closing <rdf:RDF/> around the new description instead of failing. Ported from storytold/lightcraft#3696. * craft-metadata: XmpData::has_location_metadata, every embedded XMP location has_location_metadata answers whether a packet names any Exif GPS property or a non-blank place (IPTC Core location fields, photoshop City/State/Country, IPTC Extension LocationShown and LocationCreated with a place or coordinates), including inside array items and repeated structs that the flattened map and the structured values keep only once (XmpData::names_location, from the parsed tree). The IPTC Extension namespace is now canonicalised and written. extended_xmp_guid reports the announced Extended XMP GUID. A caller that must prove a file has no location checks properties_truncated first. The source also listed LightCraft's own lc:location; a caller with its own namespace checks that itself. Ported from storytold/lightcraft#4121 (the format part). * craft-metadata: is_lens_spec_name, the inverse check of lens_spec_name Whether a lens name has the '<focal> mm f/<aperture>' shape lens_spec_name writes, so a caller can tell a made-up name from a camera's. The test is new. Ported from storytold/lightcraft#2644 (the format part). * craft-metadata: Sony focus points for 44 bodies SONY_MODELS grows from the alpha 1 and A7S III to the 44 bodies whose focus tags were checked on the public raw.pixls.us samples against ExifTool's reading; bodies whose 0x201b is not the focus mode stay out. This also covers the ILCE-6400 and ILCE-7M3 that storytold/lightcraft#3109 adds. Ported from storytold/lightcraft#1891 (the focus part). * craft-metadata: GPX points say which track they are on; tracks keep their names TrackPoint::track counts the <trk> a point came from, Tracklog::names holds each track's <name> (trimmed, at most 200 characters), and only_track gives one track's points, so a map can draw a file's tracks apart and tag from one. At most 10 000 tracks per file (TooComplex past that); a non-finite elevation is dropped. Ported from storytold/lightcraft#921 (the GPX part; #916 carries the same). * craft-metadata: test that from_embedded keeps the EXIF, IPTC, XMP precedence storytold/lightcraft#2211 adds the same function as extract_embedded; this crate already has it as from_embedded. Its tests are added: EXIF camera fields stay, IPTC fills gaps, XMP overrides the user fields, and damaged blocks read as nothing. Tests from storytold/lightcraft#2211. * craft-metadata: the XMP writer keeps a carriage return as XML end-of-line handling turns a literal CR into a line feed when a packet is read, so text with one did not round-trip through other readers. Element text now writes it as a character reference. Ported from storytold/lightcraft#4119 (the writer fix only; that PR also moves LightCraft to quick-xml 0.42, which this crate does not take here, as craft-xml uses 0.41). * craft-metadata: README rows for the ported validation and location checks --------- Co-authored-by: radialmonster <radial@gmail.com> Co-authored-by: Sebastian Berschneider <berschi@gmail.com> Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> Co-authored-by: Michael Anderson <1427851+endthestart@users.noreply.github.com> Co-authored-by: Ilya Dorman <ilya@codeforhumans.dev> Co-authored-by: Clyde C Brown <clyde.c.brown@pm.me> Co-authored-by: MohammadTeimori <teimori.mohammad@gmail.com> Co-authored-by: vangel76 <vangel1976@googlemail.com> Co-authored-by: Max Mittelstädt <62167861+TheGalitube@users.noreply.github.com> Co-authored-by: NetterSilver <133535268+Silvertree2010@users.noreply.github.com> Co-authored-by: ronibalthazar <61232335+ronibalthazar@users.noreply.github.com> Co-authored-by: Andrew Frahn <andrew@emmertex.com> Co-authored-by: jkalkstein <76634771+jkalkstein@users.noreply.github.com> Co-authored-by: d-rouge <d-rouge@users.noreply.github.com> Co-authored-by: espoon <espoon@users.noreply.github.com> Co-authored-by: Yoann Laissus <yoann.laissus@gmail.com> Co-authored-by: Jason Baldwin <33934381+bitshiftza@users.noreply.github.com> Co-authored-by: ingolfteetz <iteetz@me.com> Co-authored-by: smi-leonivkovic <leon.ivkovic@smi-digital.com>
342 lines
15 KiB
Rust
342 lines
15 KiB
Rust
//! Where the camera focused: the autofocus point a camera records in its maker notes, as a box on the
|
||
//! upright photo ([`FocusPoint`]). Sony only for now.
|
||
//!
|
||
//! **Sony** (the MakerNote IFD: header-less in ARWs, after a `SONY DSC` header in JPEGs). Tag identities and value names come from the public ExifTool
|
||
//! tag-name documentation (Sony table); every layout below was confirmed on real ILCE-1 (α1) and
|
||
//! ILCE-7SM3 (A7S III) ARWs, compared with ExifTool's output as a black box, then on the public raw.pixls.us
|
||
//! samples of every other body in [`SONY_MODELS`]. No third-party code was read.
|
||
//!
|
||
//! | Tag | Layout (confirmed) | Use |
|
||
//! |---|---|---|
|
||
//! | `0x2027` FocusLocation | 4 × int16u: the width and height of the frame it is measured in, then the focus centre x, y in pixels of that frame (the sensor's landscape frame: a portrait shot still says 8640 × 5760) | the point |
|
||
//! | `0x2037` FocusFrameSize | 6 bytes: int16u width, int16u height of the frame the camera showed, then 2 bytes that are zero when there is no frame (manual focus) | the box size |
|
||
//! | `0x201b` FocusMode | int8u: 0 Manual, 2 AF-S, 3 AF-C, 4 AF-A, 6 DMF, 7 AF-D | manual = no point |
|
||
//! | `0x201c` AFAreaModeSetting | int8u: 0 Wide, 1 Center, 3 Flexible Spot, 11 Zone, 12 Expanded Flexible Spot, 13 Custom AF Area | shown |
|
||
//! | `0x2021` AFTracking | int8u: 0 Off, 1 Face tracking, 2 Lock On AF | shown |
|
||
//! | `0x9402` (enciphered block) byte 0x16, 0x17 | FocusMode (low 7 bits) and the AF area mode actually used: 0 Multi, 1 Center, 2 Spot, 3 Flexible Spot, 11 Zone, 12 Expanded Flexible Spot, 13 Custom AF Area, 14 Tracking, 15 Face Tracking, 20 Animal Eye Tracking, 21 Human Eye Tracking, 255 Manual | shown; read only when its focus mode agrees with `0x201b` |
|
||
//!
|
||
//! The `0x94xx` blocks are enciphered byte by byte (the documentation calls it "a simple substitution
|
||
//! cipher"). On the sample files each plain byte `p < 249` is stored as `p³ mod 249` and bytes 249–255
|
||
//! as themselves (e.g. a stored `0x20` reads as AFAreaMode 20, stored `0x77` as `0x83`, FocusMode AF-C
|
||
//! with its top bit set); the map is a bijection on 0..249 (cubing is invertible mod 3 and mod 83), so
|
||
//! it is undone by a table of its inverse.
|
||
//!
|
||
//! **No real point** (nothing is stored, so nothing is drawn and Z zooms as before):
|
||
//! - a body the layout hasn't been confirmed on ([`SONY_MODELS`]), a missing or malformed tag, a zero
|
||
//! frame size, or a centre outside its frame;
|
||
//! - manual focus (`0x201b` = 0, or the block's area mode says Manual): the camera still records where
|
||
//! the AF frame was parked, not where anything was in focus (on the samples these are off-centre);
|
||
//! - the exact frame centre while the area used was Multi (Wide with nothing tracked): on the samples
|
||
//! the wide area reports the centre when it picked no particular spot. A centred Spot, Zone or
|
||
//! Flexible Spot frame is a real choice and is kept.
|
||
|
||
pub use crate::focus_read::{HEADER_PREFIX, HeaderRead, MAX_HEADER_BYTES, read_header};
|
||
use crate::{Orientation, Rect};
|
||
use craft_tiff::{ByteOrder, Ifd, Tiff, makernote, tags as t};
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
/// Where the camera focused, on the upright photo.
|
||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||
pub struct FocusPoint {
|
||
/// The focus frame, normalized to the photo's full, EXIF-oriented frame (y down, 0..1 on both
|
||
/// axes, clipped to it) — the frame face regions use, so it follows Rotate, flips and crops.
|
||
pub rect: Rect,
|
||
/// Focus mode as the camera names it (`AF-C`, `AF-S`, `DMF`…).
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub mode: Option<String>,
|
||
/// The AF area chosen on the camera (`Wide`, `Zone`, `Flexible Spot`…).
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub area: Option<String>,
|
||
/// What the camera followed, when it says (`Animal Eye Tracking`, `Face tracking`, `Lock On AF`…).
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub tracking: Option<String>,
|
||
}
|
||
|
||
impl FocusPoint {
|
||
/// The box's centre (normalized, upright).
|
||
pub fn center(&self) -> (f64, f64) {
|
||
((self.rect.x0 + self.rect.x1) / 2.0, (self.rect.y0 + self.rect.y1) / 2.0)
|
||
}
|
||
/// The words that describe it, in order (mode, area, tracking), for "AF-C · Wide · Animal Eye Tracking".
|
||
pub fn words(&self) -> Vec<&str> {
|
||
[&self.mode, &self.area, &self.tracking].into_iter().filter_map(|s| s.as_deref()).filter(|s| !s.is_empty()).collect()
|
||
}
|
||
/// The box clipped to the frame and checked: `None` when it is not a usable box (non-finite,
|
||
/// empty, or entirely outside the photo).
|
||
pub fn sanitized(mut self) -> Option<FocusPoint> {
|
||
let r = self.rect;
|
||
if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) {
|
||
return None;
|
||
}
|
||
let (x0, x1) = (r.x0.min(r.x1).clamp(0.0, 1.0), r.x0.max(r.x1).clamp(0.0, 1.0));
|
||
let (y0, y1) = (r.y0.min(r.y1).clamp(0.0, 1.0), r.y0.max(r.y1).clamp(0.0, 1.0));
|
||
if x1 - x0 <= 0.0 || y1 - y0 <= 0.0 {
|
||
return None;
|
||
}
|
||
self.rect = Rect { x0, y0, x1, y1 };
|
||
Some(self)
|
||
}
|
||
}
|
||
|
||
/// Sony bodies whose focus tags have been checked against real files. Another body may store the same
|
||
/// tags differently (or not mean the same by them): it shows no focus point until its files are checked.
|
||
///
|
||
/// The α1 and A7S III on 333 files of a photographer's library; the others on the public raw.pixls.us samples (one to
|
||
/// six ARWs per body, 103 files of the 44 bodies): every point equal to the one ExifTool's FocusLocation and
|
||
/// FocusFrameSize give (77 points, one of them rotated), every refusal (26: manual focus, Wide at the exact centre)
|
||
/// equal to what ExifTool's focus modes say, and each body's box drawn on its camera JPEG on the subject it
|
||
/// focused on (a pigeon, a face, a leaf, a chart patch). Seven of them (DSC-HX95, DSC-HX99, ILCE-6700, ILCE-7CR,
|
||
/// ILCE-7RM2, ILCE-7SM2, ILCE-9M3) only have samples without a point, read as ExifTool reads them. Not listed: the
|
||
/// bodies without `0x2027` (every NEX, SLT and DSLR-A; ILCE-3000, 3500, 5000, 5100, 6000 and 6001, QX1, 7, 7R, 7S
|
||
/// and 7M2; ILCA-68 and 77M2; RX100 to RX100 III, RX10, RX1 and RX1R; UMC-R10C), and the DSC-RX0, RX100 IV, RX100 V,
|
||
/// RX10 II, RX10 III and RX1R II, whose `0x201b` reads 0 (Manual) while the enciphered block says AF-S: ExifTool
|
||
/// doesn't decode that tag for them.
|
||
pub const SONY_MODELS: &[&str] = &[
|
||
"DSC-HX95",
|
||
"DSC-HX99",
|
||
"DSC-RX0M2",
|
||
"DSC-RX100M5A",
|
||
"DSC-RX100M6",
|
||
"DSC-RX100M7",
|
||
"DSC-RX100M7A",
|
||
"DSC-RX10M4",
|
||
"DSC-RX1RM3",
|
||
"ILCA-99M2",
|
||
"ILCE-1",
|
||
"ILCE-1M2",
|
||
"ILCE-6100",
|
||
"ILCE-6300",
|
||
"ILCE-6400",
|
||
"ILCE-6400A",
|
||
"ILCE-6500",
|
||
"ILCE-6600",
|
||
"ILCE-6700",
|
||
"ILCE-7C",
|
||
"ILCE-7CM2",
|
||
"ILCE-7CR",
|
||
"ILCE-7M3",
|
||
"ILCE-7M4",
|
||
"ILCE-7M5",
|
||
"ILCE-7RM2",
|
||
"ILCE-7RM3",
|
||
"ILCE-7RM3A",
|
||
"ILCE-7RM4",
|
||
"ILCE-7RM4A",
|
||
"ILCE-7RM5",
|
||
"ILCE-7SM2",
|
||
"ILCE-7SM3",
|
||
"ILCE-9",
|
||
"ILCE-9M2",
|
||
"ILCE-9M3",
|
||
"ILME-FX2",
|
||
"ILME-FX3",
|
||
"ILME-FX30",
|
||
"ZV-1",
|
||
"ZV-1M2",
|
||
"ZV-E1",
|
||
"ZV-E10",
|
||
"ZV-E10M2",
|
||
];
|
||
|
||
/// Whether a camera as the catalog names it (`"SONY ILCE-1"`: the Exif Make, a space, the Model) is
|
||
/// one whose files can carry a focus point, so a photo from any other camera is never opened to look.
|
||
pub fn camera_supported(camera: &str) -> bool {
|
||
let camera = camera.trim();
|
||
camera.get(..4).is_some_and(|m| m.eq_ignore_ascii_case("SONY")) && camera.rsplit(' ').next().is_some_and(|model| SONY_MODELS.contains(&model))
|
||
}
|
||
|
||
/// Names what [`read`] decodes (its bodies), so a record of "looked, found nothing" made by this
|
||
/// decoder is not trusted by one that knows more bodies.
|
||
pub fn decoder_tag() -> String {
|
||
format!("sony-v1:{}", SONY_MODELS.join(","))
|
||
}
|
||
|
||
const FOCUS_MODE: u16 = 0x201b;
|
||
const AF_AREA_SETTING: u16 = 0x201c;
|
||
const AF_TRACKING: u16 = 0x2021;
|
||
const FOCUS_LOCATION: u16 = 0x2027;
|
||
const FOCUS_FRAME_SIZE: u16 = 0x2037;
|
||
const TAG_9402: u16 = 0x9402;
|
||
|
||
/// Side of the box drawn when the camera gave a point but no frame size, as a fraction of the frame's
|
||
/// short side (about the size of the α1's smallest frames).
|
||
const DEFAULT_SIDE: f64 = 0.03;
|
||
|
||
/// The focus point a file's maker note records, or `None` (see the module notes for when).
|
||
/// `data` is the TIFF stream the maker note's offsets refer to (a whole raw, or an Exif block).
|
||
pub fn read(data: &[u8], tiff: &Tiff, make: Option<&str>, model: Option<&str>, orientation: Option<Orientation>) -> Option<FocusPoint> {
|
||
let make = make?;
|
||
if !make.to_ascii_uppercase().starts_with("SONY") || !SONY_MODELS.contains(&model?.trim()) {
|
||
return None;
|
||
}
|
||
let e = tiff.exif()?.get(t::MAKER_NOTE)?;
|
||
let mn = makernote::parse_makernote(data, e.offset, e.count() as u64, tiff.order, make)?;
|
||
// ARWs from these bodies carry a header-less IFD; their JPEGs the `SONY DSC` header
|
||
if !matches!(mn.kind, makernote::MakerNoteKind::Sony | makernote::MakerNoteKind::Plain) {
|
||
return None;
|
||
}
|
||
sony(&mn.ifd, mn.order, orientation.unwrap_or_default())
|
||
}
|
||
|
||
fn byte(ifd: &Ifd, tag: u16) -> Option<u8> {
|
||
ifd.value(tag)?.get_u64(0).and_then(|v| u8::try_from(v).ok())
|
||
}
|
||
|
||
/// Decode the Sony tags of a parsed maker-note IFD.
|
||
pub(crate) fn sony(ifd: &Ifd, order: ByteOrder, orientation: Orientation) -> Option<FocusPoint> {
|
||
let loc = ifd.value(FOCUS_LOCATION)?;
|
||
let [w, h, x, y] = [0, 1, 2, 3].map(|i| loc.get_u64(i));
|
||
let (w, h, x, y) = (w? as f64, h? as f64, x? as f64, y? as f64);
|
||
if w < 1.0 || h < 1.0 || x > w || y > h {
|
||
return None;
|
||
}
|
||
let mode = byte(ifd, FOCUS_MODE);
|
||
if mode == Some(0) {
|
||
return None;
|
||
}
|
||
// the enciphered block: its focus mode must agree with the plain one, else its layout is not the one we know
|
||
let block = ifd.bytes(TAG_9402).and_then(|b| {
|
||
let (m, area) = (decipher(*b.get(0x16)?) & 0x7f, decipher(*b.get(0x17)?));
|
||
(Some(m) == mode).then_some(area)
|
||
});
|
||
if block == Some(255) {
|
||
return None;
|
||
}
|
||
let setting = byte(ifd, AF_AREA_SETTING);
|
||
let tracking = byte(ifd, AF_TRACKING);
|
||
let wide_untracked = match block {
|
||
Some(a) => a == 0,
|
||
None => setting == Some(0) && tracking.is_none_or(|t| t == 0),
|
||
};
|
||
if wide_untracked && x * 2.0 == w && y * 2.0 == h {
|
||
return None;
|
||
}
|
||
// frame size: two int16u in the note's byte order, then a non-zero marker when there is a frame
|
||
let size = ifd.bytes(FOCUS_FRAME_SIZE).and_then(|b| {
|
||
let (fw, fh) = (order.read_u16(b, 0)? as f64, order.read_u16(b, 2)? as f64);
|
||
let shown = b.get(4..6).is_none_or(|m| m.iter().any(|&v| v != 0));
|
||
(shown && fw >= 1.0 && fh >= 1.0).then_some((fw, fh))
|
||
});
|
||
let (fw, fh) = size.unwrap_or_else(|| {
|
||
let side = w.min(h) * DEFAULT_SIDE;
|
||
(side, side)
|
||
});
|
||
let sensor = Rect { x0: (x - fw / 2.0) / w, y0: (y - fh / 2.0) / h, x1: (x + fw / 2.0) / w, y1: (y + fh / 2.0) / h };
|
||
let name = |v: Option<u8>, f: fn(u8) -> Option<&'static str>| v.and_then(f).map(str::to_string);
|
||
let area = name(setting, area_setting_name);
|
||
let used = name(block, area_used_name);
|
||
// what it followed: the area mode used when it says more than the setting (Animal Eye Tracking on
|
||
// Wide), else the tracking setting when it is on
|
||
let tracking = used.filter(|u| Some(u) != area.as_ref() && u != "Multi").or_else(|| name(tracking, tracking_name).filter(|t| t != "Off"));
|
||
FocusPoint { rect: orientation.map_norm_rect(sensor), mode: name(mode, focus_mode_name), area, tracking }.sanitized()
|
||
}
|
||
|
||
/// A minimal little-endian TIFF laid out as an α1 ARW's metadata is (IFD0 with Make `SONY` and Model `ILCE-1` →
|
||
/// Exif IFD → a header-less maker note with the focus tags: AF-C or the given FocusMode byte, Wide, Face tracking,
|
||
/// Animal Eye Tracking at (3226, 1980) of 8640 × 5760), followed by `samples` bytes standing in for sensor data. For
|
||
/// tests of the readers and the backfill in other crates; not a real raw (it has no image).
|
||
#[doc(hidden)]
|
||
pub fn synthetic_arw(mode: u8, samples: usize) -> Vec<u8> {
|
||
fn entry(f: &mut Vec<u8>, tag: u16, typ: u16, count: u32, value: [u8; 4]) {
|
||
f.extend_from_slice(&tag.to_le_bytes());
|
||
f.extend_from_slice(&typ.to_le_bytes());
|
||
f.extend_from_slice(&count.to_le_bytes());
|
||
f.extend_from_slice(&value);
|
||
}
|
||
let encipher = |p: u8| if p >= 249 { p } else { (u32::from(p).pow(3) % 249) as u8 };
|
||
let mut f = b"II*\0".to_vec();
|
||
f.extend_from_slice(&8u32.to_le_bytes());
|
||
// IFD0 at 8: Make (at 62), Model (at 68), Orientation, the Exif IFD (at 76)
|
||
f.extend_from_slice(&4u16.to_le_bytes());
|
||
entry(&mut f, t::MAKE, 2, 5, 62u32.to_le_bytes());
|
||
entry(&mut f, t::MODEL, 2, 7, 68u32.to_le_bytes());
|
||
entry(&mut f, t::ORIENTATION, 3, 1, [1, 0, 0, 0]);
|
||
entry(&mut f, t::EXIF_IFD, 4, 1, 76u32.to_le_bytes());
|
||
f.extend_from_slice(&[0; 4]);
|
||
f.extend_from_slice(b"SONY\0\0ILCE-1\0\0");
|
||
// the Exif IFD: the maker note at 94, 156 bytes
|
||
f.extend_from_slice(&1u16.to_le_bytes());
|
||
entry(&mut f, t::MAKER_NOTE, 7, 156, 94u32.to_le_bytes());
|
||
f.extend_from_slice(&[0; 4]);
|
||
// the maker note's IFD, its values from 172
|
||
f.extend_from_slice(&6u16.to_le_bytes());
|
||
entry(&mut f, FOCUS_MODE, 1, 1, [mode, 0, 0, 0]);
|
||
entry(&mut f, AF_AREA_SETTING, 1, 1, [0, 0, 0, 0]);
|
||
entry(&mut f, AF_TRACKING, 1, 1, [1, 0, 0, 0]);
|
||
entry(&mut f, FOCUS_LOCATION, 3, 4, 172u32.to_le_bytes());
|
||
entry(&mut f, FOCUS_FRAME_SIZE, 7, 6, 180u32.to_le_bytes());
|
||
entry(&mut f, TAG_9402, 7, 64, 186u32.to_le_bytes());
|
||
f.extend_from_slice(&[0; 4]);
|
||
for v in [8640u16, 5760, 3226, 1980] {
|
||
f.extend_from_slice(&v.to_le_bytes());
|
||
}
|
||
f.extend_from_slice(&[0xaf, 0, 0xb4, 0, 1, 1]);
|
||
let mut block = [0u8; 64];
|
||
block[0x16] = encipher(0x80 | mode);
|
||
block[0x17] = encipher(20);
|
||
f.extend_from_slice(&block);
|
||
f.extend((0..samples).map(|i| (i % 251) as u8));
|
||
f
|
||
}
|
||
|
||
/// Undo the `0x94xx` byte substitution: the stored byte is `p³ mod 249` for `p < 249`.
|
||
fn decipher(b: u8) -> u8 {
|
||
if b >= 249 {
|
||
return b;
|
||
}
|
||
(0..249u32).find(|p| (p * p * p) % 249 == u32::from(b)).and_then(|p| u8::try_from(p).ok()).unwrap_or(b)
|
||
}
|
||
|
||
fn focus_mode_name(v: u8) -> Option<&'static str> {
|
||
Some(match v {
|
||
0 => "Manual",
|
||
2 => "AF-S",
|
||
3 => "AF-C",
|
||
4 => "AF-A",
|
||
6 => "DMF",
|
||
7 => "AF-D",
|
||
_ => return None,
|
||
})
|
||
}
|
||
|
||
fn area_setting_name(v: u8) -> Option<&'static str> {
|
||
Some(match v {
|
||
0 => "Wide",
|
||
1 | 9 => "Center",
|
||
3 | 4 => "Flexible Spot",
|
||
11 => "Zone",
|
||
12 => "Expanded Flexible Spot",
|
||
13 => "Custom AF Area",
|
||
_ => return None,
|
||
})
|
||
}
|
||
|
||
fn tracking_name(v: u8) -> Option<&'static str> {
|
||
Some(match v {
|
||
0 => "Off",
|
||
1 => "Face tracking",
|
||
2 => "Lock On AF",
|
||
_ => return None,
|
||
})
|
||
}
|
||
|
||
fn area_used_name(v: u8) -> Option<&'static str> {
|
||
Some(match v {
|
||
0 => "Multi",
|
||
1 => "Center",
|
||
2 => "Spot",
|
||
3 => "Flexible Spot",
|
||
11 => "Zone",
|
||
12 => "Expanded Flexible Spot",
|
||
13 => "Custom AF Area",
|
||
14 => "Tracking",
|
||
15 => "Face Tracking",
|
||
20 => "Animal Eye Tracking",
|
||
21 => "Human Eye Tracking",
|
||
_ => return None,
|
||
})
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests;
|