Skip to main content

cosmic_applet_avestruz/
media.rs

1// SPDX-License-Identifier: MIT
2
3//! A file that is to be attached to a note, before it goes anywhere: what
4//! kind of file it is, how large a picture it is, and the picture without
5//! what it says of where, when, with what and by whom it was made.
6//!
7//! A photograph says a good deal more than what it shows: where it was
8//! taken, when, with which camera, what it was edited with, who it is
9//! credited to, and sometimes a smaller copy of what it showed before it
10//! was cropped. None of that is for a media server, or for whoever looks
11//! at the note. So a JPEG, a PNG or a WebP is sent as the picture and no
12//! more: of what the file is made of, only what the picture needs to look
13//! as it did is kept, and everything else is left out, whatever it is.
14//!
15//! | Format | Kept | Left out |
16//! |---|---|---|
17//! | JPEG | The tables, frames and scans; of the application segments, the JFIF header, the colour profile (ICC) and Adobe's colour marker | Every other application segment (EXIF, XMP, IPTC, MPF, content credentials, makers' own), the comments, and whatever follows the end of the picture |
18//! | PNG | The header, the palette, the picture data, transparency, colour (gamma, chromaticities, sRGB, ICC, HDR), pixel size, background, animation | Every other chunk (text, EXIF, the time it was changed, content credentials, makers' own), and whatever follows the end |
19//! | WebP | The picture data, alpha, the colour profile, animation | EXIF, XMP, and every chunk that is none of those |
20//!
21//! This is done to the bytes of the file, and the picture data is copied
22//! as it is: nothing is decoded and encoded again, so nothing of the
23//! picture is lost.
24//!
25//! One thing is put back. A camera held sideways writes the picture as its
26//! sensor saw it and says in the EXIF which way is up; without that the
27//! picture lies on its side. Which way is up says nothing of where or with
28//! what, so a picture that is not upright as written gets an EXIF block
29//! that says that and nothing else.
30//!
31//! What comes out is then decoded, to make sure it is still a picture. If
32//! it is not, while the file as it was is, the file is refused
33//! ([`MediaError::Damaged`]) rather than sent as it was: what was to be
34//! left out is still in it.
35//!
36//! Other files go as they are: a GIF, a video, a sound. **A video may say
37//! where it was taken**, and that is not taken out of it here.
38
39use std::io::Cursor;
40
41use image::ImageFormat;
42
43/// The largest file that is attached. It is read into memory whole, to be
44/// hashed and sent.
45pub const MAX_BYTES: usize = 100_000_000;
46
47/// What a file that is not known to be anything is called.
48const ANY: &str = "application/octet-stream";
49
50/// A file ready to be sent to a media server.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Media {
53    /// What it was called where it was picked.
54    pub name: String,
55    /// What it is made of, as it is sent.
56    pub bytes: Vec<u8>,
57    /// What kind of file it is: its MIME type.
58    pub mime: &'static str,
59    /// How wide and how tall it shows, in pixels, if it is a picture that
60    /// could be measured.
61    pub dim: Option<(u32, u32)>,
62}
63
64/// Why a file is not attached.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum MediaError {
67    /// There is nothing in it.
68    Empty,
69    /// It is larger than [`MAX_BYTES`]: this many bytes.
70    TooLarge(usize),
71    /// It is a picture whose file is not put together as its format
72    /// says, so what it says beside the picture could not be left out.
73    Unreadable,
74    /// It was a picture, and is not one any more with what it says
75    /// beside the picture left out.
76    Damaged,
77}
78
79/// What kind of file `bytes` are, by how they start; or, for what does not
80/// say, by what the name `name` ends in.
81pub fn kind_of(bytes: &[u8], name: &str) -> &'static str {
82    let extension = name.rsplit_once('.').map(|(_, extension)| extension.to_ascii_lowercase()).unwrap_or_default();
83    match bytes {
84        [0xFF, 0xD8, 0xFF, ..] => "image/jpeg",
85        [0x89, b'P', b'N', b'G', ..] => "image/png",
86        [b'G', b'I', b'F', b'8', ..] => "image/gif",
87        [b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => "image/webp",
88        [b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'A', b'V', b'E', ..] => "audio/wav",
89        [b'B', b'M', ..] if extension == "bmp" => "image/bmp",
90        [0x1A, 0x45, 0xDF, 0xA3, ..] if extension == "mkv" => "video/x-matroska",
91        [0x1A, 0x45, 0xDF, 0xA3, ..] => "video/webm",
92        [b'O', b'g', b'g', b'S', ..] => "audio/ogg",
93        [b'f', b'L', b'a', b'C', ..] => "audio/flac",
94        [b'I', b'D', b'3', ..] => "audio/mpeg",
95        [_, _, _, _, b'f', b't', b'y', b'p', brand @ ..] => match brand.get(..4) {
96            Some(b"avif" | b"avis") => "image/avif",
97            Some(b"heic" | b"heix" | b"heif" | b"mif1") => "image/heic",
98            Some(b"qt  ") => "video/quicktime",
99            Some(b"M4A " | b"M4B ") => "audio/mp4",
100            _ => "video/mp4",
101        },
102        _ => match extension.as_str() {
103            "svg" => "image/svg+xml",
104            "mp3" => "audio/mpeg",
105            "mp4" | "m4v" => "video/mp4",
106            "mov" => "video/quicktime",
107            "webm" => "video/webm",
108            "pdf" => "application/pdf",
109            "txt" => "text/plain",
110            _ => ANY,
111        },
112    }
113}
114
115/// The file called `name` that `bytes` are, ready to be sent: a JPEG, a PNG
116/// or a WebP as the picture and no more (see the [module](self)), and
117/// anything else as it is.
118pub fn prepare(name: String, bytes: Vec<u8>) -> Result<Media, MediaError> {
119    if bytes.is_empty() {
120        return Err(MediaError::Empty);
121    }
122    if bytes.len() > MAX_BYTES {
123        return Err(MediaError::TooLarge(bytes.len()));
124    }
125    let mime = kind_of(&bytes, &name);
126    let bared = match mime {
127        "image/jpeg" => Some((bare_jpeg(&bytes), ImageFormat::Jpeg)),
128        "image/png" => Some((bare_png(&bytes), ImageFormat::Png)),
129        "image/webp" => Some((bare_webp(&bytes), ImageFormat::WebP)),
130        _ => None,
131    };
132    let Some((bare, format)) = bared else {
133        // Not cleaned: measured by its header, if it is a picture at all.
134        let measured = image::ImageReader::new(Cursor::new(&bytes)).with_guessed_format().ok();
135        let dim = measured.and_then(|reader| reader.into_dimensions().ok());
136        return Ok(Media { name, bytes, mime, dim });
137    };
138    let bare = bare.ok_or(MediaError::Unreadable)?;
139    let decoded =
140        |bytes: &[u8]| image::load_from_memory_with_format(bytes, format).ok().map(|picture| (picture.width(), picture.height()));
141    let dim = match decoded(&bare.bytes) {
142        // Shown on its side, it is as wide as it is written tall.
143        Some((width, height)) if bare.orientation.is_some_and(|orientation| orientation >= 5) => Some((height, width)),
144        Some(size) => Some(size),
145        // What can't be decoded either way is not for this to judge.
146        None if decoded(&bytes).is_none() => None,
147        None => return Err(MediaError::Damaged),
148    };
149    Ok(Media { name, bytes: bare.bytes, mime, dim })
150}
151
152/// A picture's file with nothing in it but the picture, and which way up
153/// the file it was made from said the picture is: 1 to 8, as EXIF counts
154/// them, where 1 is as written.
155struct Bare {
156    bytes: Vec<u8>,
157    orientation: Option<u16>,
158}
159
160/// The EXIF tag that says which way up a picture is.
161const ORIENTATION_TAG: u16 = 0x0112;
162
163/// Which way up the EXIF block `tiff` says its picture is, if it says, and
164/// says one of the eight there are. An EXIF block is a TIFF file: a
165/// header that says which end its numbers start at and where its first
166/// directory is, and that directory, twelve bytes to an entry.
167fn orientation_in(tiff: &[u8]) -> Option<u16> {
168    let little = match tiff.get(..2)? {
169        b"II" => true,
170        b"MM" => false,
171        _ => return None,
172    };
173    let short = |at: usize| -> Option<u16> {
174        let bytes: [u8; 2] = tiff.get(at..at.checked_add(2)?)?.try_into().ok()?;
175        Some(if little { u16::from_le_bytes(bytes) } else { u16::from_be_bytes(bytes) })
176    };
177    let long = |at: usize| -> Option<u32> {
178        let bytes: [u8; 4] = tiff.get(at..at.checked_add(4)?)?.try_into().ok()?;
179        Some(if little { u32::from_le_bytes(bytes) } else { u32::from_be_bytes(bytes) })
180    };
181    if short(2)? != 0x002A {
182        return None;
183    }
184    let directory = usize::try_from(long(4)?).ok()?;
185    let entries = usize::from(short(directory)?);
186    for entry in 0..entries {
187        let at = directory.checked_add(2 + entry * 12)?;
188        if short(at)? == ORIENTATION_TAG {
189            let orientation = short(at.checked_add(8)?)?;
190            return (1..=8).contains(&orientation).then_some(orientation);
191        }
192    }
193    None
194}
195
196/// An EXIF block that says the picture is `orientation` way up, and
197/// nothing else: a directory of that one entry.
198fn orientation_only(orientation: u16) -> [u8; 26] {
199    let mut tiff = [0; 26];
200    tiff[..4].copy_from_slice(b"MM\0\x2A");
201    // The directory follows the header, which is eight bytes.
202    tiff[4..8].copy_from_slice(&8u32.to_be_bytes());
203    tiff[8..10].copy_from_slice(&1u16.to_be_bytes());
204    tiff[10..12].copy_from_slice(&ORIENTATION_TAG.to_be_bytes());
205    // One short, which is in the entry itself. No directory follows.
206    tiff[12..14].copy_from_slice(&3u16.to_be_bytes());
207    tiff[14..18].copy_from_slice(&1u32.to_be_bytes());
208    tiff[18..20].copy_from_slice(&orientation.to_be_bytes());
209    tiff
210}
211
212/// The orientation that is to be said again: one that is not as written.
213fn to_say(orientation: Option<u16>) -> Option<u16> {
214    orientation.filter(|orientation| *orientation != 1)
215}
216
217/// How a JPEG's EXIF segment starts, before the EXIF block.
218const JPEG_EXIF: &[u8] = b"Exif\0\0";
219
220/// Whether the segment of a JPEG marked `marker`, which holds `payload`,
221/// is part of the picture. Everything is, but the application segments
222/// and the comments; and of the application segments the JFIF header,
223/// the colour profile, and Adobe's marker, which says how the colours
224/// are written.
225fn jpeg_keeps(marker: u8, payload: &[u8]) -> bool {
226    match marker {
227        0xE0 => payload.starts_with(b"JFIF\0"),
228        0xE2 => payload.starts_with(b"ICC_PROFILE\0"),
229        0xEE => payload.starts_with(b"Adobe"),
230        0xE1 | 0xE3..=0xED | 0xEF | 0xFE => false,
231        _ => true,
232    }
233}
234
235/// Where the picture data that starts at `from` in the JPEG `bytes` ends:
236/// at the next marker that is none of its own, which are the stuffed
237/// zero, the restart markers and fill bytes.
238fn end_of_scan(bytes: &[u8], from: usize) -> usize {
239    let rest = bytes.get(from..).unwrap_or_default();
240    let marker = rest.windows(2).position(|pair| matches!(pair, [0xFF, next] if !matches!(next, 0x00 | 0xD0..=0xD7 | 0xFF)));
241    marker.map_or(bytes.len(), |marker| from + marker)
242}
243
244/// The JPEG `bytes` as the picture and no more. `None` if it is not put
245/// together as a JPEG is.
246///
247/// A JPEG is a row of segments, each a marker and, for most, a length and
248/// that much data; after a start of scan comes picture data, up to the
249/// next marker. It ends at the end-of-image marker, and what follows that
250/// is no part of the picture: a second picture, a video of the moment.
251fn bare_jpeg(bytes: &[u8]) -> Option<Bare> {
252    if !bytes.starts_with(&[0xFF, 0xD8]) {
253        return None;
254    }
255    let mut out = Vec::with_capacity(bytes.len());
256    out.extend_from_slice(&[0xFF, 0xD8]);
257    // The orientation goes after the JFIF header, which has to be first
258    // where there is one, and first otherwise.
259    let mut exif_at = out.len();
260    let mut orientation = None;
261    let mut at = 2;
262    // A file that ends short of its end marker is copied as far as it goes.
263    while let Some(&start) = bytes.get(at) {
264        if start != 0xFF {
265            return None;
266        }
267        let marker = *bytes.get(at + 1)?;
268        match marker {
269            // A fill byte before the marker.
270            0xFF => at += 1,
271            0xD9 => {
272                out.extend_from_slice(&[0xFF, 0xD9]);
273                break;
274            }
275            // Markers that stand alone.
276            0x01 | 0xD0..=0xD8 => {
277                out.extend_from_slice(&[0xFF, marker]);
278                at += 2;
279            }
280            _ => {
281                let length = usize::from(u16::from_be_bytes(bytes.get(at + 2..at + 4)?.try_into().ok()?));
282                if length < 2 {
283                    return None;
284                }
285                let end = at + 2 + length;
286                let segment = bytes.get(at..end)?;
287                let payload = segment.get(4..)?;
288                if marker == 0xE1
289                    && let Some(tiff) = payload.strip_prefix(JPEG_EXIF)
290                {
291                    orientation = orientation.or_else(|| orientation_in(tiff));
292                }
293                if jpeg_keeps(marker, payload) {
294                    out.extend_from_slice(segment);
295                    if marker == 0xE0 && out.len() == exif_at + segment.len() {
296                        exif_at = out.len();
297                    }
298                }
299                at = end;
300                if marker == 0xDA {
301                    let scan_end = end_of_scan(bytes, at);
302                    out.extend_from_slice(bytes.get(at..scan_end)?);
303                    at = scan_end;
304                }
305            }
306        }
307    }
308    if let Some(orientation) = to_say(orientation) {
309        let tiff = orientation_only(orientation);
310        let length = u16::try_from(2 + JPEG_EXIF.len() + tiff.len()).ok()?;
311        let segment: Vec<u8> = [&[0xFF, 0xE1][..], &length.to_be_bytes(), JPEG_EXIF, &tiff].concat();
312        out.splice(exif_at..exif_at, segment);
313    }
314    Some(Bare { bytes: out, orientation })
315}
316
317/// How a PNG starts.
318const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
319
320/// The chunks of a PNG that are part of the picture: its header, palette
321/// and data; transparency; what its colours are (gamma, chromaticities,
322/// sRGB, a profile, significant bits, and the three that say how bright
323/// and in which colour space); how large a pixel is; its background;
324/// suggested palettes; and animation.
325const PNG_KEPT: [&[u8; 4]; 20] = [
326    b"IHDR", b"PLTE", b"IDAT", b"IEND", b"tRNS", b"gAMA", b"cHRM", b"sRGB", b"iCCP", b"sBIT", b"cICP", b"mDCV", b"cLLI", b"pHYs",
327    b"bKGD", b"hIST", b"sPLT", b"acTL", b"fcTL", b"fdAT",
328];
329
330/// The checksum a PNG chunk ends in, of its name and what it holds, which
331/// are `bytes`: CRC-32.
332fn png_crc(bytes: &[u8]) -> u32 {
333    let mut crc = u32::MAX;
334    for byte in bytes {
335        crc ^= u32::from(*byte);
336        for _ in 0..8 {
337            crc = if crc & 1 == 1 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 };
338        }
339    }
340    !crc
341}
342
343/// The PNG chunk called `name` that holds `data`.
344fn png_chunk(name: &[u8; 4], data: &[u8]) -> Vec<u8> {
345    let named: Vec<u8> = [&name[..], data].concat();
346    let length = u32::try_from(data.len()).unwrap_or_default();
347    [&length.to_be_bytes()[..], &named, &png_crc(&named).to_be_bytes()].concat()
348}
349
350/// The PNG `bytes` as the picture and no more. `None` if it is not put
351/// together as a PNG is.
352///
353/// A PNG is a row of chunks after its signature: each a length, a name of
354/// four letters, that much data, and a checksum. The header is first and
355/// the end chunk last; what follows that is no part of the picture.
356fn bare_png(bytes: &[u8]) -> Option<Bare> {
357    let mut rest = bytes.strip_prefix(PNG_SIGNATURE)?;
358    let mut out = Vec::with_capacity(bytes.len());
359    out.extend_from_slice(PNG_SIGNATURE);
360    let mut header_end = None;
361    let mut orientation = None;
362    loop {
363        let length = usize::try_from(u32::from_be_bytes(rest.get(..4)?.try_into().ok()?)).ok()?;
364        let chunk = rest.get(..length.checked_add(12)?)?;
365        let name: &[u8; 4] = chunk.get(4..8)?.try_into().ok()?;
366        if name == b"eXIf" {
367            orientation = orientation.or_else(|| orientation_in(chunk.get(8..8 + length).unwrap_or_default()));
368        }
369        if PNG_KEPT.contains(&name) {
370            out.extend_from_slice(chunk);
371        }
372        if name == b"IHDR" && header_end.is_none() {
373            header_end = Some(out.len());
374        }
375        rest = rest.get(chunk.len()..)?;
376        if name == b"IEND" {
377            break;
378        }
379    }
380    // Before the picture data, where whoever shows it knows in time.
381    if let (Some(orientation), Some(at)) = (to_say(orientation), header_end) {
382        out.splice(at..at, png_chunk(b"eXIf", &orientation_only(orientation)));
383    }
384    Some(Bare { bytes: out, orientation })
385}
386
387/// The chunks of a WebP that are part of the picture: its data, lossy or
388/// lossless; the header of the extended format; alpha; the colour
389/// profile; and animation.
390const WEBP_KEPT: [&[u8; 4]; 7] = [b"VP8 ", b"VP8L", b"VP8X", b"ALPH", b"ICCP", b"ANIM", b"ANMF"];
391
392/// In the header of the extended format, the flags that say there is
393/// EXIF, and that there is XMP.
394const WEBP_HAS_EXIF: u8 = 0x08;
395const WEBP_HAS_XMP: u8 = 0x04;
396
397/// The WebP `bytes` as the picture and no more. `None` if it is not put
398/// together as a WebP is.
399///
400/// A WebP is a RIFF file: a header that says how long it is, then chunks,
401/// each a name of four letters, a length, and that much data, padded to an
402/// even length. In the extended format the first chunk is a header whose
403/// flags say which others there are.
404fn bare_webp(bytes: &[u8]) -> Option<Bare> {
405    if bytes.get(..4)? != b"RIFF" || bytes.get(8..12)? != b"WEBP" {
406        return None;
407    }
408    let said = usize::try_from(u32::from_le_bytes(bytes.get(4..8)?.try_into().ok()?)).ok()?;
409    // What follows what the header counts is no part of the file.
410    let mut rest = bytes.get(12..said.checked_add(8)?.min(bytes.len()))?;
411    let mut out = Vec::with_capacity(bytes.len());
412    out.extend_from_slice(bytes.get(..12)?);
413    let mut orientation = None;
414    while !rest.is_empty() {
415        let name: &[u8; 4] = rest.get(..4)?.try_into().ok()?;
416        let length = usize::try_from(u32::from_le_bytes(rest.get(4..8)?.try_into().ok()?)).ok()?;
417        let data = rest.get(8..length.checked_add(8)?)?;
418        // The last chunk may come without its padding.
419        let padded = (8 + length + length % 2).min(rest.len());
420        if name == b"EXIF" {
421            // Some write it as a JPEG does, after a header of its own.
422            let tiff = data.strip_prefix(JPEG_EXIF).unwrap_or(data);
423            orientation = orientation.or_else(|| orientation_in(tiff));
424        }
425        if WEBP_KEPT.contains(&name) {
426            out.extend_from_slice(rest.get(..8 + length)?);
427            if length % 2 == 1 {
428                out.push(0);
429            }
430        }
431        rest = rest.get(padded..)?;
432    }
433    // Only the extended format has anything but the picture data, and
434    // says in its header what.
435    if out.get(12..16) == Some(b"VP8X") {
436        let flags = out.get_mut(20)?;
437        *flags &= !(WEBP_HAS_EXIF | WEBP_HAS_XMP);
438        if let Some(orientation) = to_say(orientation) {
439            *flags |= WEBP_HAS_EXIF;
440            let tiff = orientation_only(orientation);
441            out.extend_from_slice(b"EXIF");
442            out.extend_from_slice(&u32::try_from(tiff.len()).ok()?.to_le_bytes());
443            out.extend_from_slice(&tiff);
444        }
445    }
446    let length = u32::try_from(out.len() - 8).ok()?;
447    out.get_mut(4..8)?.copy_from_slice(&length.to_le_bytes());
448    Some(Bare { bytes: out, orientation })
449}
450
451#[cfg(test)]
452mod tests {
453    use super::{
454        JPEG_EXIF, MAX_BYTES, MediaError, PNG_SIGNATURE, bare_jpeg, bare_png, bare_webp, kind_of, orientation_in,
455        orientation_only, png_chunk, png_crc, prepare,
456    };
457    use image::metadata::Orientation;
458    use image::{DynamicImage, ImageDecoder, ImageFormat, Rgb, RgbImage};
459    use std::io::Cursor;
460
461    /// A picture three wide and two tall, each pixel a colour of its own.
462    fn picture() -> DynamicImage {
463        DynamicImage::ImageRgb8(RgbImage::from_fn(3, 2, |x, y| Rgb([(x * 80) as u8, (y * 120) as u8, 200])))
464    }
465
466    fn encoded(format: ImageFormat) -> Vec<u8> {
467        let mut bytes = Vec::new();
468        picture().write_to(&mut Cursor::new(&mut bytes), format).unwrap();
469        bytes
470    }
471
472    /// An EXIF block, numbers little end first, that says where the
473    /// picture was taken and that it is `orientation` way up.
474    fn exif(orientation: u16) -> Vec<u8> {
475        let mut tiff = b"II\x2A\0".to_vec();
476        tiff.extend_from_slice(&8u32.to_le_bytes());
477        tiff.extend_from_slice(&2u16.to_le_bytes());
478        // Where: a pointer to the GPS directory.
479        tiff.extend_from_slice(&[0x25, 0x88, 4, 0, 1, 0, 0, 0, 38, 0, 0, 0]);
480        tiff.extend_from_slice(&[0x12, 0x01, 3, 0, 1, 0, 0, 0]);
481        tiff.extend_from_slice(&orientation.to_le_bytes());
482        tiff.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
483        tiff.extend_from_slice(b"GPS: 38.7223 N, 9.1393 W");
484        tiff
485    }
486
487    /// The JPEG segment marked `marker` that holds `payload`.
488    fn segment(marker: u8, payload: &[u8]) -> Vec<u8> {
489        let length = u16::try_from(payload.len() + 2).unwrap();
490        [&[0xFF, marker][..], &length.to_be_bytes(), payload].concat()
491    }
492
493    /// A JPEG as a camera and an editor leave it: `plain` with everything
494    /// said beside the picture put in after its JFIF header, the picture
495    /// `orientation` way up, and a video after its end.
496    fn laden_jpeg(plain: &[u8], orientation: u16) -> Vec<u8> {
497        // After the start marker comes the JFIF header, 18 bytes of it.
498        let (head, rest) = plain.split_at(20);
499        assert_eq!(&head[2..4], [0xFF, 0xE0]);
500        [
501            head,
502            &segment(0xE1, &[JPEG_EXIF, &exif(orientation)].concat()),
503            &segment(0xE1, b"http://ns.adobe.com/xap/1.0/\0<x:xmpmeta>creator: Fernando</x:xmpmeta>"),
504            &segment(0xE2, b"ICC_PROFILE\0\x01\x01a colour profile"),
505            &segment(0xE2, b"MPF\0a second picture"),
506            &segment(0xEB, b"JP\0\0c2pa: signed by Fernando"),
507            &segment(0xED, b"Photoshop 3.0\08BIM caption: at home"),
508            &segment(0xFE, b"a comment: taken with my phone"),
509            rest,
510            b"a video of the moment",
511        ]
512        .concat()
513    }
514
515    fn has(bytes: &[u8], needle: &[u8]) -> bool {
516        bytes.windows(needle.len()).any(|window| window == needle)
517    }
518
519    fn pixels(bytes: &[u8], format: ImageFormat) -> Vec<u8> {
520        image::load_from_memory_with_format(bytes, format).unwrap().into_rgb8().into_raw()
521    }
522
523    fn orientation_of(bytes: &[u8], format: ImageFormat) -> Orientation {
524        let mut reader = image::ImageReader::with_format(Cursor::new(bytes), format).into_decoder().unwrap();
525        reader.orientation().unwrap()
526    }
527
528    #[test]
529    fn a_file_is_known_by_how_it_starts_and_failing_that_by_its_name() {
530        assert_eq!(kind_of(&encoded(ImageFormat::Jpeg), "picture"), "image/jpeg");
531        assert_eq!(kind_of(&encoded(ImageFormat::Png), "picture.jpg"), "image/png");
532        assert_eq!(kind_of(&encoded(ImageFormat::WebP), "picture"), "image/webp");
533        assert_eq!(kind_of(&encoded(ImageFormat::Gif), "picture"), "image/gif");
534        assert_eq!(kind_of(b"\0\0\0\x20ftypisom\0\0\x02\0", "clip"), "video/mp4");
535        assert_eq!(kind_of(b"\0\0\0\x14ftypqt  \0\0\0\0", "clip"), "video/quicktime");
536        assert_eq!(kind_of(b"\0\0\0\x1cftypavif\0\0\0\0", "picture"), "image/avif");
537        assert_eq!(kind_of(b"\x1A\x45\xDF\xA3\x01", "clip"), "video/webm");
538        assert_eq!(kind_of(b"ID3\x04\0", "song"), "audio/mpeg");
539        assert_eq!(kind_of(b"<svg xmlns='http://www.w3.org/2000/svg'/>", "Drawing.SVG"), "image/svg+xml");
540        assert_eq!(kind_of(b"anything at all", "notes.xyz"), "application/octet-stream");
541    }
542
543    #[test]
544    fn which_way_up_is_read_from_exif_written_either_end_first_and_written_back_alone() {
545        assert_eq!(orientation_in(&exif(6)), Some(6));
546        for orientation in 1..=8 {
547            assert_eq!(orientation_in(&orientation_only(orientation)), Some(orientation));
548        }
549        assert_eq!(orientation_in(&exif(9)), None, "there are eight ways up");
550        assert_eq!(orientation_in(b"II\x2A\0\xFF\xFF\xFF\xFF"), None, "a directory that is not there");
551        assert_eq!(orientation_in(b"not a TIFF header"), None);
552        assert_eq!(orientation_in(b""), None);
553    }
554
555    #[test]
556    fn a_jpeg_keeps_its_picture_its_colours_and_which_way_up_and_nothing_else() {
557        let plain = encoded(ImageFormat::Jpeg);
558        let laden = laden_jpeg(&plain, 6);
559        let bare = bare_jpeg(&laden).unwrap();
560
561        for told in [&b"GPS"[..], b"Fernando", b"second picture", b"c2pa", b"at home", b"my phone", b"video"] {
562            assert!(has(&laden, told) && !has(&bare.bytes, told), "{} is left out", String::from_utf8_lossy(told));
563        }
564        assert!(has(&bare.bytes, b"a colour profile"), "the colour profile stays");
565        assert!(has(&bare.bytes, b"JFIF\0"));
566        assert_eq!(pixels(&bare.bytes, ImageFormat::Jpeg), pixels(&plain, ImageFormat::Jpeg), "the picture is as it was");
567        assert_eq!(bare.orientation, Some(6));
568        assert_eq!(orientation_of(&bare.bytes, ImageFormat::Jpeg), Orientation::Rotate90);
569        // What says so is after the JFIF header, and all the EXIF there is.
570        assert_eq!(&bare.bytes[20..24], [0xFF, 0xE1, 0, 34]);
571        assert!(bare.bytes.ends_with(&[0xFF, 0xD9]), "it ends where the picture does");
572    }
573
574    #[test]
575    fn a_jpeg_that_is_upright_as_written_says_nothing_beside_the_picture() {
576        let plain = encoded(ImageFormat::Jpeg);
577        assert_eq!(bare_jpeg(&plain).unwrap().bytes, plain, "a JPEG that is only the picture is left as it is");
578
579        let bare = bare_jpeg(&laden_jpeg(&plain, 1)).unwrap();
580        assert!(!has(&bare.bytes, b"Exif"));
581        // The picture as it was encoded, and its colour profile.
582        let profile = segment(0xE2, b"ICC_PROFILE\0\x01\x01a colour profile");
583        assert_eq!(bare.bytes, [&plain[..20], &profile, &plain[20..]].concat());
584    }
585
586    #[test]
587    fn a_jpeg_that_is_not_put_together_as_one_is_not_a_picture_to_send() {
588        let plain = encoded(ImageFormat::Jpeg);
589        assert!(bare_jpeg(b"not a JPEG").is_none());
590        // A segment that says it is longer than the file.
591        assert!(bare_jpeg(&[&plain[..2], &[0xFF, 0xE1, 0xFF, 0xFF, 1, 2, 3]].concat()).is_none());
592        // One that says it is shorter than its own length.
593        assert!(bare_jpeg(&[&plain[..2], &[0xFF, 0xE1, 0, 1, 1, 2, 3]].concat()).is_none());
594        // Something between two segments that is no marker.
595        assert!(bare_jpeg(&[&plain[..20], &[0x12, 0x34], &plain[20..]].concat()).is_none());
596        // One cut short is copied as far as it goes.
597        let short = &plain[..plain.len() - 2];
598        assert_eq!(bare_jpeg(short).unwrap().bytes, short);
599    }
600
601    /// A PNG as an editor leaves it: `plain` with everything said beside
602    /// the picture put in after its header, the picture `orientation` way
603    /// up, and something after its end.
604    fn laden_png(plain: &[u8], orientation: u16) -> Vec<u8> {
605        // The signature, and the header chunk: 13 bytes in 12 of chunk.
606        let (head, rest) = plain.split_at(8 + 25);
607        [
608            head,
609            &png_chunk(b"gAMA", &45_455u32.to_be_bytes()),
610            &png_chunk(b"tEXt", b"Author\0Fernando"),
611            &png_chunk(b"iTXt", b"XML:com.adobe.xmp\0\0\0\0\0<x:xmpmeta>at home</x:xmpmeta>"),
612            &png_chunk(b"eXIf", &exif(orientation)),
613            &png_chunk(b"tIME", &[7, 233, 1, 22, 6, 53, 25]),
614            &png_chunk(b"caBX", b"c2pa: signed"),
615            &png_chunk(b"prVt", b"a maker's own"),
616            rest,
617            b"something after the end",
618        ]
619        .concat()
620    }
621
622    #[test]
623    fn the_checksum_of_a_png_chunk_is_the_one_a_png_ends_with() {
624        // The end chunk holds nothing, and is the same in every PNG.
625        assert_eq!(png_crc(b"IEND"), 0xAE42_6082);
626        assert!(encoded(ImageFormat::Png).ends_with(&png_chunk(b"IEND", b"")));
627    }
628
629    #[test]
630    fn a_png_keeps_its_picture_its_colours_and_which_way_up_and_nothing_else() {
631        let plain = encoded(ImageFormat::Png);
632        let laden = laden_png(&plain, 8);
633        let bare = bare_png(&laden).unwrap();
634
635        for told in [&b"GPS"[..], b"Fernando", b"at home", b"tIME", b"c2pa", b"maker", b"after the end"] {
636            assert!(has(&laden, told) && !has(&bare.bytes, told), "{} is left out", String::from_utf8_lossy(told));
637        }
638        assert!(has(&bare.bytes, b"gAMA"), "what its colours are stays");
639        assert_eq!(pixels(&bare.bytes, ImageFormat::Png), pixels(&plain, ImageFormat::Png), "the picture is as it was");
640        assert_eq!(bare.orientation, Some(8));
641        assert_eq!(orientation_of(&bare.bytes, ImageFormat::Png), Orientation::Rotate270);
642
643        let upright = bare_png(&laden_png(&plain, 1)).unwrap();
644        assert!(!has(&upright.bytes, b"eXIf"), "upright as written, it says nothing of which way up");
645        assert_eq!(bare_png(&plain).unwrap().bytes, plain, "a PNG that is only the picture is left as it is");
646    }
647
648    #[test]
649    fn an_animated_png_stays_animated() {
650        let animated = [
651            PNG_SIGNATURE,
652            &png_chunk(b"IHDR", &[0; 13]),
653            &png_chunk(b"acTL", &[0, 0, 0, 2, 0, 0, 0, 0]),
654            &png_chunk(b"fcTL", &[0; 26]),
655            &png_chunk(b"IDAT", b"the first frame"),
656            &png_chunk(b"fcTL", &[1; 26]),
657            &png_chunk(b"fdAT", b"the second frame"),
658            &png_chunk(b"IEND", b""),
659        ]
660        .concat();
661        assert_eq!(bare_png(&animated).unwrap().bytes, animated);
662    }
663
664    #[test]
665    fn a_png_that_is_not_put_together_as_one_is_not_a_picture_to_send() {
666        let plain = encoded(ImageFormat::Png);
667        assert!(bare_png(b"not a PNG").is_none());
668        assert!(bare_png(&plain[..plain.len() - 12]).is_none(), "it has no end");
669        assert!(
670            bare_png(&[PNG_SIGNATURE, &[0xFF, 0xFF, 0xFF, 0xFF], b"IHDR"].concat()).is_none(),
671            "a chunk longer than the file"
672        );
673    }
674
675    /// The WebP chunk called `name` that holds `data`.
676    fn webp_chunk(name: &[u8; 4], data: &[u8]) -> Vec<u8> {
677        let length = u32::try_from(data.len()).unwrap();
678        let padding: &[u8] = if data.len() % 2 == 1 { &[0] } else { &[] };
679        [&name[..], &length.to_le_bytes(), data, padding].concat()
680    }
681
682    /// The WebP that holds `chunks`.
683    fn webp(chunks: &[Vec<u8>]) -> Vec<u8> {
684        let chunks = chunks.concat();
685        let length = u32::try_from(chunks.len() + 4).unwrap();
686        [&b"RIFF"[..], &length.to_le_bytes(), b"WEBP", &chunks].concat()
687    }
688
689    #[test]
690    fn a_webp_keeps_its_picture_its_colours_and_which_way_up_and_nothing_else() {
691        // The header of the extended format: its flags, three bytes kept
692        // for later, and how large the picture is.
693        let header = |flags: u8| webp_chunk(b"VP8X", &[flags, 0, 0, 0, 2, 0, 0, 1, 0, 0]);
694        let profile = webp_chunk(b"ICCP", b"a colour profile");
695        let data = webp_chunk(b"VP8 ", b"the picture");
696        let exif_of = |orientation| webp_chunk(b"EXIF", &exif(orientation));
697        let xmp = webp_chunk(b"XMP ", b"<x:xmpmeta>creator: Fernando</x:xmpmeta>");
698        let unknown = webp_chunk(b"MAKR", b"a maker's own");
699        // A profile, EXIF and XMP: 0x20, 0x08 and 0x04.
700        let laden = [
701            webp(&[header(0x2C), profile.clone(), data.clone(), exif_of(3), xmp.clone(), unknown.clone()]),
702            b"after it".to_vec(),
703        ]
704        .concat();
705
706        let bare = bare_webp(&laden).unwrap();
707        assert_eq!(bare.orientation, Some(3));
708        let said = webp_chunk(b"EXIF", &orientation_only(3));
709        assert_eq!(
710            bare.bytes,
711            webp(&[header(0x28), profile.clone(), data.clone(), said]),
712            "the profile, the picture, and which way up"
713        );
714
715        let upright = webp(&[header(0x2C), profile.clone(), data.clone(), exif_of(1), xmp, unknown]);
716        assert_eq!(
717            bare_webp(&upright).unwrap().bytes,
718            webp(&[header(0x20), profile, data]),
719            "upright as written, it has no EXIF"
720        );
721    }
722
723    #[test]
724    fn a_webp_that_is_only_the_picture_is_left_as_it_is() {
725        let plain = encoded(ImageFormat::WebP);
726        assert_eq!(bare_webp(&plain).unwrap().bytes, plain);
727        assert!(bare_webp(b"RIFF\x04\0\0\0WAVE").is_none());
728        assert!(bare_webp(&webp(&[b"VP8 \xFF\xFF\0\0short".to_vec()])).is_none(), "a chunk longer than the file");
729    }
730
731    #[test]
732    fn a_picture_is_made_ready_bare_and_measured_as_it_shows() {
733        let plain = encoded(ImageFormat::Jpeg);
734        let sideways = prepare("holiday.jpg".into(), laden_jpeg(&plain, 6)).unwrap();
735        assert_eq!(sideways.mime, "image/jpeg");
736        assert!(!has(&sideways.bytes, b"GPS"));
737        assert_eq!(sideways.dim, Some((2, 3)), "three wide as written, it shows two wide on its side");
738
739        let upright = prepare("holiday.png".into(), laden_png(&encoded(ImageFormat::Png), 1)).unwrap();
740        assert_eq!((upright.mime, upright.dim), ("image/png", Some((3, 2))));
741        assert!(!has(&upright.bytes, b"Fernando"));
742
743        let gif = encoded(ImageFormat::Gif);
744        let as_it_is = prepare("dance.gif".into(), gif.clone()).unwrap();
745        assert_eq!((as_it_is.mime, as_it_is.dim, as_it_is.bytes), ("image/gif", Some((3, 2)), gif));
746
747        let clip = b"\0\0\0\x20ftypisom and the rest of a video".to_vec();
748        let video = prepare("clip.mp4".into(), clip.clone()).unwrap();
749        assert_eq!((video.mime, video.dim, video.bytes), ("video/mp4", None, clip));
750    }
751
752    #[test]
753    fn what_cannot_be_made_ready_is_refused_and_says_why() {
754        assert_eq!(prepare("empty.jpg".into(), Vec::new()), Err(MediaError::Empty));
755        assert_eq!(prepare("huge.bin".into(), vec![0; MAX_BYTES + 1]), Err(MediaError::TooLarge(MAX_BYTES + 1)));
756        // It starts as a JPEG does, and is not put together as one.
757        assert_eq!(prepare("broken.jpg".into(), b"\xFF\xD8\xFF\xE1\xFF\xFF".to_vec()), Err(MediaError::Unreadable));
758    }
759}