1use std::io::Cursor;
40
41use image::ImageFormat;
42
43pub const MAX_BYTES: usize = 100_000_000;
46
47const ANY: &str = "application/octet-stream";
49
50#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Media {
53 pub name: String,
55 pub bytes: Vec<u8>,
57 pub mime: &'static str,
59 pub dim: Option<(u32, u32)>,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum MediaError {
67 Empty,
69 TooLarge(usize),
71 Unreadable,
74 Damaged,
77}
78
79pub 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
115pub 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 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 Some((width, height)) if bare.orientation.is_some_and(|orientation| orientation >= 5) => Some((height, width)),
144 Some(size) => Some(size),
145 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
152struct Bare {
156 bytes: Vec<u8>,
157 orientation: Option<u16>,
158}
159
160const ORIENTATION_TAG: u16 = 0x0112;
162
163fn 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
196fn orientation_only(orientation: u16) -> [u8; 26] {
199 let mut tiff = [0; 26];
200 tiff[..4].copy_from_slice(b"MM\0\x2A");
201 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 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
212fn to_say(orientation: Option<u16>) -> Option<u16> {
214 orientation.filter(|orientation| *orientation != 1)
215}
216
217const JPEG_EXIF: &[u8] = b"Exif\0\0";
219
220fn 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
235fn 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
244fn 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 let mut exif_at = out.len();
260 let mut orientation = None;
261 let mut at = 2;
262 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 0xFF => at += 1,
271 0xD9 => {
272 out.extend_from_slice(&[0xFF, 0xD9]);
273 break;
274 }
275 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
317const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
319
320const 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
330fn 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
343fn 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
350fn 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 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
387const WEBP_KEPT: [&[u8; 4]; 7] = [b"VP8 ", b"VP8L", b"VP8X", b"ALPH", b"ICCP", b"ANIM", b"ANMF"];
391
392const WEBP_HAS_EXIF: u8 = 0x08;
395const WEBP_HAS_XMP: u8 = 0x04;
396
397fn 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 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 let padded = (8 + length + length % 2).min(rest.len());
420 if name == b"EXIF" {
421 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 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 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 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 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 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 fn laden_jpeg(plain: &[u8], orientation: u16) -> Vec<u8> {
497 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 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 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 assert!(bare_jpeg(&[&plain[..2], &[0xFF, 0xE1, 0xFF, 0xFF, 1, 2, 3]].concat()).is_none());
592 assert!(bare_jpeg(&[&plain[..2], &[0xFF, 0xE1, 0, 1, 1, 2, 3]].concat()).is_none());
594 assert!(bare_jpeg(&[&plain[..20], &[0x12, 0x34], &plain[20..]].concat()).is_none());
596 let short = &plain[..plain.len() - 2];
598 assert_eq!(bare_jpeg(short).unwrap().bytes, short);
599 }
600
601 fn laden_png(plain: &[u8], orientation: u16) -> Vec<u8> {
605 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 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 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 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 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 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 assert_eq!(prepare("broken.jpg".into(), b"\xFF\xD8\xFF\xE1\xFF\xFF".to_vec()), Err(MediaError::Unreadable));
758 }
759}