1use pdf2::{Dictionary, Document, Object, Stream};
4
5use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
6use crate::geom::{Matrix, Point};
7use crate::{Error, Result};
8
9#[derive(Debug, Clone)]
11pub struct Image {
12 width: u32,
13 height: u32,
14 pixels: Vec<Color>,
15 interpolate: bool,
16 masked: Option<Vec<bool>>,
18}
19
20impl Image {
21 pub fn from_stream(
27 document: &Document,
28 stream: &Stream,
29 id: Option<pdf2::ObjectId>,
30 ) -> Result<Self> {
31 let dict = stream.dict();
32 if is_jpx(dict) {
39 return Self::from_jpx(document, stream, id);
40 }
41 if is_jbig2(dict) {
42 return Self::from_jbig2(document, stream, id);
43 }
44 let width = integer(dict, b"Width")?;
45 let height = integer(dict, b"Height")?;
46 if width == 0 || height == 0 {
47 return Err(Error::malformed("image with zero width or height"));
48 }
49 let bits = dict
50 .get(b"BitsPerComponent")
51 .and_then(Object::as_integer)
52 .unwrap_or(8);
53 if bits != 8 && bits != 1 {
56 return Err(Error::malformed(
57 "only 1 and 8 bits per component images are rendered",
58 ));
59 }
60 let interpolate = matches!(dict.get(b"Interpolate"), Some(Object::Boolean(true)));
61 let space = resolve(document, dict.get(b"ColorSpace"))?;
62 let colours = ColourSpace::from_object(document, space)?;
68 let per_pixel = colours.components();
69 let count = (width as usize)
70 .checked_mul(height as usize)
71 .and_then(|pixels| pixels.checked_mul(per_pixel))
72 .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
73 let limit = document.decoded_limit();
74 if count > limit {
75 return Err(Error::Limit {
76 what: "an image of the /Width and /Height it declares",
77 limit,
78 });
79 }
80 let key = match dict.get(b"Mask") {
85 None => None,
86 Some(Object::Array(items)) => Some(ColourKey::parse(items, per_pixel, bits)?),
87 Some(Object::Reference(_)) => {
88 return Err(Error::Unsupported {
89 what: "a /Mask image stencil",
90 });
91 }
92 Some(_) => {
93 return Err(Error::malformed(
94 "a /Mask that is neither an array nor a stream",
95 ));
96 }
97 };
98 if key.is_some() && is_dct(dict) {
99 return Err(Error::Unsupported {
100 what: "colour-key /Mask on a /DCTDecode image",
101 });
102 }
103 if is_dct(dict) {
104 return Self::from_dct(document, stream, id, interpolate);
105 }
106 let decoded = document.decode_stream(stream)?;
107 let data = if bits == 1 {
108 widen_one_bit(&decoded, width, height, per_pixel)?
109 } else {
110 decoded
111 };
112 if data.len() < count {
113 return Err(Error::Malformed {
114 what: "image data is shorter than width × height × components",
115 offset: None,
116 });
117 }
118 let masked = key.map(|key| {
122 data.chunks_exact(per_pixel)
123 .map(|sample| key.masks(sample))
124 .collect::<Vec<bool>>()
125 });
126 let decode = decode_ranges(dict.get(b"Decode"), per_pixel);
127 let mut pixels = Vec::with_capacity((width as usize) * (height as usize));
128 for index in (0..count).step_by(per_pixel) {
129 let sample = &data[index..index + per_pixel];
130 let mut components = [0.0_f64; 4];
131 for (slot, byte) in sample.iter().enumerate().take(per_pixel) {
132 let (from, to) = decode[slot];
133 components[slot] = (from + f64::from(*byte) / 255.0 * (to - from)).clamp(0.0, 1.0);
134 }
135 pixels.push(colour_at(&colours, &components));
136 }
137 Ok(Self {
138 width,
139 height,
140 pixels,
141 interpolate,
142 masked,
143 })
144 }
145
146 #[cfg(feature = "dct")]
154 fn from_dct(
155 document: &Document,
156 _stream: &Stream,
157 id: Option<pdf2::ObjectId>,
158 interpolate: bool,
159 ) -> Result<Self> {
160 let Some(id) = id else {
161 return Err(Error::malformed(
162 "a /DCTDecode image without an object number",
163 ));
164 };
165 let data = document.stream_bytes(id)?;
166 let cmyk = dict_component_count(_stream) == Some(4);
172 let mut decoder =
173 zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&data));
174 if cmyk {
175 decoder.set_options(
176 zune_jpeg::zune_core::options::DecoderOptions::default()
177 .jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK),
178 );
179 }
180 let pixels = decoder
181 .decode()
182 .map_err(|_| Error::malformed("/DCTDecode payload"))?;
183 let Some(info) = decoder.info() else {
184 return Err(Error::malformed(
185 "/DCTDecode payload without a frame header",
186 ));
187 };
188 let components = match decoder.output_colorspace() {
189 Some(zune_jpeg::zune_core::colorspace::ColorSpace::Luma) => 1,
190 Some(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK) => 4,
191 _ => 3,
192 };
193 let count = usize::from(info.width)
194 .checked_mul(usize::from(info.height))
195 .and_then(|samples| samples.checked_mul(components))
196 .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
197 let limit = document.decoded_limit();
198 if count > limit {
199 return Err(Error::Limit {
200 what: "a /DCTDecode image of the size its header declares",
201 limit,
202 });
203 }
204 if pixels.len() < count {
205 return Err(Error::malformed(
206 "/DCTDecode payload is shorter than its header",
207 ));
208 }
209 let stated_decode = _stream.dict().get(b"Decode").is_some();
215 let invert = cmyk && !stated_decode && has_adobe_marker(&data);
216 let decode = decode_ranges(_stream.dict().get(b"Decode"), components);
219 let sample = |bytes: &[u8]| -> Vec<f64> {
220 bytes
221 .iter()
222 .enumerate()
223 .map(|(index, byte)| {
224 let value = f64::from(*byte) / 255.0;
225 let (from, to) = decode[index.min(decode.len() - 1)];
226 (from + value * (to - from)).clamp(0.0, 1.0)
227 })
228 .collect()
229 };
230 let pixels = pixels[..count]
231 .chunks_exact(components)
232 .map(|bytes| {
233 let bytes: Vec<u8> = if invert {
234 bytes.iter().map(|byte| 255 - byte).collect()
235 } else {
236 bytes.to_vec()
237 };
238 let values = sample(&bytes);
239 match components {
240 1 => Color::rgb(values[0], values[0], values[0]),
241 4 => Color::from_cmyk(values[0], values[1], values[2], values[3]),
242 _ => Color::rgb(values[0], values[1], values[2]),
243 }
244 })
245 .collect();
246 Ok(Self {
247 width: u32::from(info.width),
248 height: u32::from(info.height),
249 pixels,
250 interpolate,
251 masked: None,
254 })
255 }
256
257 #[cfg(not(feature = "dct"))]
259 fn from_dct(
260 _document: &Document,
261 _stream: &Stream,
262 _id: Option<pdf2::ObjectId>,
263 _interpolate: bool,
264 ) -> Result<Self> {
265 Err(Error::Unsupported {
266 what: "/DCTDecode images (build with the `dct` feature)",
267 })
268 }
269
270 #[cfg(not(feature = "jpx"))]
272 fn from_jpx(
273 _document: &Document,
274 _stream: &Stream,
275 _id: Option<pdf2::ObjectId>,
276 ) -> Result<Self> {
277 Err(Error::Unsupported {
278 what: "/JPXDecode images (build with the `jpx` feature)",
279 })
280 }
281
282 #[cfg(feature = "jpx")]
286 fn from_jpx(document: &Document, stream: &Stream, id: Option<pdf2::ObjectId>) -> Result<Self> {
287 let Some(id) = id else {
288 return Err(Error::malformed(
289 "a /JPXDecode image without an object number",
290 ));
291 };
292 let interpolate = matches!(
293 stream.dict().get(b"Interpolate"),
294 Some(Object::Boolean(true))
295 );
296 let data = document.stream_bytes(id)?;
297 let image = hayro_jpeg2000::Image::new(&data, &hayro_jpeg2000::DecodeSettings::default())
298 .map_err(|_| Error::malformed("/JPXDecode codestream"))?;
299 if image.has_alpha() {
303 return Err(Error::Unsupported {
304 what: "a /JPXDecode image with an alpha channel",
305 });
306 }
307 let components = jpx_components(image.color_space())?;
308 let width = image.width();
309 let height = image.height();
310 let count = (width as usize)
311 .checked_mul(height as usize)
312 .and_then(|pixels| pixels.checked_mul(components))
313 .ok_or_else(|| Error::malformed("/JPXDecode image dimensions overflow"))?;
314 let limit = document.decoded_limit();
315 if count > limit {
316 return Err(Error::Limit {
317 what: "a /JPXDecode image of the size its codestream declares",
318 limit,
319 });
320 }
321 let mut context = hayro_jpeg2000::DecoderContext::default();
324 let decoded = image
325 .decode(&mut context)
326 .map_err(|_| Error::malformed("/JPXDecode payload"))?;
327 let samples = decoded.data_u8();
328 if samples.len() < count {
329 return Err(Error::malformed(
330 "/JPXDecode payload is shorter than its header",
331 ));
332 }
333 let sample = |byte: u8| f64::from(byte) / 255.0;
334 let pixels = samples[..count]
335 .chunks_exact(components)
336 .map(|bytes| match components {
337 1 => {
338 let grey = sample(bytes[0]);
339 Color::rgb(grey, grey, grey)
340 }
341 4 => Color::from_cmyk(
342 sample(bytes[0]),
343 sample(bytes[1]),
344 sample(bytes[2]),
345 sample(bytes[3]),
346 ),
347 _ => Color::rgb(sample(bytes[0]), sample(bytes[1]), sample(bytes[2])),
348 })
349 .collect();
350 Ok(Self {
351 width,
352 height,
353 pixels,
354 interpolate,
355 masked: None,
356 })
357 }
358
359 #[cfg(not(feature = "jbig2"))]
361 fn from_jbig2(
362 _document: &Document,
363 _stream: &Stream,
364 _id: Option<pdf2::ObjectId>,
365 ) -> Result<Self> {
366 Err(Error::Unsupported {
367 what: "/JBIG2Decode images (build with the `jbig2` feature)",
368 })
369 }
370
371 #[cfg(feature = "jbig2")]
375 fn from_jbig2(
376 document: &Document,
377 stream: &Stream,
378 id: Option<pdf2::ObjectId>,
379 ) -> Result<Self> {
380 let Some(id) = id else {
381 return Err(Error::malformed(
382 "a /JBIG2Decode image without an object number",
383 ));
384 };
385 let interpolate = matches!(
386 stream.dict().get(b"Interpolate"),
387 Some(Object::Boolean(true))
388 );
389 let settings = hayro_jbig2::DecodeSettings::default();
390 let globals = match globals_bytes(document, stream.dict())? {
394 Some(bytes) => Some(
395 hayro_jbig2::Globals::new(&bytes, &settings)
396 .map_err(|_| Error::malformed("/JBIG2Decode globals stream"))?,
397 ),
398 None => None,
399 };
400 let data = document.stream_bytes(id)?;
401 let page = hayro_jbig2::Page::new_embedded(&data, globals.as_ref(), &settings)
402 .map_err(|_| Error::malformed("/JBIG2Decode page"))?;
403 let width = page.width();
404 let height = page.height();
405 let count = (width as usize)
406 .checked_mul(height as usize)
407 .ok_or_else(|| Error::malformed("/JBIG2Decode image dimensions overflow"))?;
408 let limit = document.decoded_limit();
409 if count > limit {
410 return Err(Error::Limit {
411 what: "a /JBIG2Decode image of the size its page information declares",
412 limit,
413 });
414 }
415 let mut rows = Rows::new(width as usize, height as usize);
416 page.decode(&mut rows)
417 .map_err(|_| Error::malformed("/JBIG2Decode payload"))?;
418 let widened = widen_one_bit(&rows.finish(), width, height, 1)?;
419 let decode = decode_ranges(stream.dict().get(b"Decode"), 1);
424 let (from, to) = decode[0];
425 let pixels = widened
426 .into_iter()
427 .map(|sample| {
428 let value = f64::from(sample) / 255.0;
429 let grey = (from + value * (to - from)).clamp(0.0, 1.0);
430 Color::rgb(grey, grey, grey)
431 })
432 .collect();
433 Ok(Self {
434 width,
435 height,
436 pixels,
437 interpolate,
438 masked: None,
439 })
440 }
441
442 fn is_masked(&self, u: f64, v: f64) -> bool {
444 let Some(masked) = &self.masked else {
445 return false;
446 };
447 if self.width == 0 || self.height == 0 {
448 return false;
449 }
450 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
451 let x = (u.clamp(0.0, 1.0) * f64::from(self.width)) as u32;
452 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
453 let y = (v.clamp(0.0, 1.0) * f64::from(self.height)) as u32;
454 let x = x.min(self.width - 1);
455 let y = y.min(self.height - 1);
456 masked
457 .get((y * self.width + x) as usize)
458 .copied()
459 .unwrap_or(false)
460 }
461
462 pub fn width(&self) -> u32 {
464 self.width
465 }
466
467 pub fn height(&self) -> u32 {
469 self.height
470 }
471
472 pub fn sample(&self, u: f64, v: f64) -> Color {
474 if self.width == 0 || self.height == 0 {
475 return Color::WHITE;
476 }
477 let x = (u.clamp(0.0, 1.0) * f64::from(self.width) - 0.5).max(0.0);
478 let y = (v.clamp(0.0, 1.0) * f64::from(self.height) - 0.5).max(0.0);
479 if !self.interpolate {
480 return self.pixel(x.round() as u32, y.round() as u32);
481 }
482 let x0 = x.floor() as u32;
483 let y0 = y.floor() as u32;
484 let x1 = (x0 + 1).min(self.width - 1);
485 let y1 = (y0 + 1).min(self.height - 1);
486 let fx = x - f64::from(x0);
487 let fy = y - f64::from(y0);
488 let top = mix(self.pixel(x0, y0), self.pixel(x1, y0), fx);
489 let bottom = mix(self.pixel(x0, y1), self.pixel(x1, y1), fx);
490 mix(top, bottom, fy)
491 }
492
493 fn pixel(&self, x: u32, y: u32) -> Color {
494 let x = x.min(self.width - 1);
495 let y = y.min(self.height - 1);
496 self.pixels[(y as usize) * (self.width as usize) + (x as usize)]
497 }
498
499 pub fn paint(
501 &self,
502 canvas: &mut Canvas,
503 mask: &ClipMask,
504 ctm: Matrix,
505 alpha: f64,
506 mode: BlendMode,
507 ) {
508 let Some(inverse) = ctm.invert() else {
509 return;
510 };
511 let corners = [
512 ctm.apply(Point::new(0.0, 0.0)),
513 ctm.apply(Point::new(1.0, 0.0)),
514 ctm.apply(Point::new(0.0, 1.0)),
515 ctm.apply(Point::new(1.0, 1.0)),
516 ];
517 let min_x = corners
518 .iter()
519 .fold(f64::INFINITY, |min, point| min.min(point.x))
520 .floor()
521 .max(0.0);
522 let max_x = corners
523 .iter()
524 .fold(f64::NEG_INFINITY, |max, point| max.max(point.x))
525 .ceil()
526 .min(f64::from(canvas.width()));
527 let min_y = corners
528 .iter()
529 .fold(f64::INFINITY, |min, point| min.min(point.y))
530 .floor()
531 .max(0.0);
532 let max_y = corners
533 .iter()
534 .fold(f64::NEG_INFINITY, |max, point| max.max(point.y))
535 .ceil()
536 .min(f64::from(canvas.height()));
537 for y in min_y as u32..max_y as u32 {
538 for x in min_x as u32..max_x as u32 {
539 let coverage = mask.alpha(x, y);
540 if coverage <= 0.0 {
541 continue;
542 }
543 let device = Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
544 let user = inverse.apply(device);
545 if !(0.0..=1.0).contains(&user.x) || !(0.0..=1.0).contains(&user.y) {
546 continue;
547 }
548 let v = 1.0 - user.y;
551 if self.is_masked(user.x, v) {
552 continue;
556 }
557 let colour = self.sample(user.x, v);
558 canvas.blend_with(x, y, colour, alpha * coverage, mode);
559 }
560 }
561 }
562}
563
564#[derive(Debug, Clone, PartialEq, Eq)]
570struct ColourKey {
571 min: [u8; 4],
572 max: [u8; 4],
573 components: usize,
574}
575
576impl ColourKey {
577 fn parse(items: &[Object], components: usize, bits: i64) -> Result<Self> {
580 if items.len() != components * 2 {
581 return Err(Error::malformed(
582 "a /Mask whose length is not twice the image's component count",
583 ));
584 }
585 let scale = if bits == 1 { 255.0 } else { 1.0 };
586 let limit = if bits == 1 { 1.0 } else { 255.0 };
587 let mut min = [0_u8; 4];
588 let mut max = [0_u8; 4];
589 for slot in 0..components {
590 let low = items[slot * 2].as_real().unwrap_or(-1.0);
591 let high = items[slot * 2 + 1].as_real().unwrap_or(-1.0);
592 if !(0.0..=limit).contains(&low) || !(0.0..=limit).contains(&high) {
593 return Err(Error::malformed("a /Mask value outside the sample range"));
594 }
595 min[slot] = (low * scale).round() as u8;
596 max[slot] = (high * scale).round() as u8;
597 }
598 Ok(Self {
599 min,
600 max,
601 components,
602 })
603 }
604
605 fn masks(&self, sample: &[u8]) -> bool {
607 sample
608 .iter()
609 .take(self.components)
610 .enumerate()
611 .all(|(slot, byte)| (self.min[slot]..=self.max[slot]).contains(byte))
612 }
613}
614
615fn decode_ranges(decode: Option<&Object>, components: usize) -> Vec<(f64, f64)> {
617 let mut ranges = vec![(0.0, 1.0); components];
618 let Some(Object::Array(items)) = decode else {
619 return ranges;
620 };
621 if items.len() < components * 2 {
622 return ranges;
623 }
624 for (slot, pair) in items.as_chunks::<2>().0.iter().enumerate().take(components) {
625 let (Some(from), Some(to)) = (pair[0].as_real(), pair[1].as_real()) else {
626 continue;
627 };
628 ranges[slot] = (from, to);
629 }
630 ranges
631}
632
633fn colour_at(colours: &ColourSpace, components: &[f64; 4]) -> Color {
635 match colours {
636 ColourSpace::Gray => Color::rgb(components[0], components[0], components[0]),
637 ColourSpace::Rgb => Color::rgb(components[0], components[1], components[2]),
638 ColourSpace::Cmyk => {
639 Color::from_cmyk(components[0], components[1], components[2], components[3])
640 }
641 ColourSpace::Indexed { base, lookup } => {
642 let index = (components[0] * 255.0).round().max(0.0) as usize;
645 let count = base.components();
646 let entry = index * count;
647 let slice = lookup.get(entry..entry + count).unwrap_or(&[]);
648 if slice.len() < count {
649 return Color::BLACK;
650 }
651 let mut table = [0.0_f64; 4];
652 for (slot, byte) in slice.iter().enumerate().take(4) {
653 table[slot] = f64::from(*byte) / 255.0;
654 }
655 colour_at(base, &table)
656 }
657 }
658}
659
660fn mix(left: Color, right: Color, t: f64) -> Color {
661 let t = t.clamp(0.0, 1.0);
662 Color::rgb(
663 left.r * (1.0 - t) + right.r * t,
664 left.g * (1.0 - t) + right.g * t,
665 left.b * (1.0 - t) + right.b * t,
666 )
667}
668
669#[derive(Debug, Clone, PartialEq)]
671enum ColourSpace {
672 Gray,
673 Rgb,
674 Cmyk,
675 Indexed {
676 base: Box<ColourSpace>,
677 lookup: Vec<u8>,
678 },
679}
680
681impl ColourSpace {
682 fn from_object(document: &Document, object: Object) -> Result<Self> {
683 match object {
684 Object::Name(name) => match name.as_slice() {
685 b"DeviceGray" | b"G" | b"CalGray" => Ok(Self::Gray),
686 b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(Self::Rgb),
687 b"DeviceCMYK" | b"CMYK" => Ok(Self::Cmyk),
688 _ => Err(Error::malformed("unsupported image /ColorSpace")),
689 },
690 Object::Array(items) => {
691 let family = match items.first() {
692 Some(Object::Name(name)) => name.clone(),
693 _ => return Err(Error::malformed("image /ColorSpace array family")),
694 };
695 match family.as_slice() {
696 b"Indexed" | b"I" => {
697 let base = match items.get(1) {
698 Some(base) => {
699 Self::from_object(document, resolve(document, Some(base))?)?
700 }
701 None => return Err(Error::malformed("Indexed image without a base")),
702 };
703 let lookup = match items.get(3) {
704 Some(Object::String(string)) => string.as_bytes().to_vec(),
705 Some(Object::Reference(id)) => document.stream_data(*id)?,
706 _ => {
707 return Err(Error::malformed(
708 "Indexed image without a lookup table",
709 ));
710 }
711 };
712 Ok(Self::Indexed {
713 base: Box::new(base),
714 lookup,
715 })
716 }
717 b"ICCBased" => {
718 match crate::shading::icc_components(document, &items)? {
722 crate::shading::Space::Gray => Ok(Self::Gray),
723 crate::shading::Space::Rgb => Ok(Self::Rgb),
724 crate::shading::Space::Cmyk => Ok(Self::Cmyk),
725 _ => Err(Error::Unsupported {
726 what: "an /ICCBased image in a tint space",
727 }),
728 }
729 }
730 _ => Err(Error::malformed("unsupported image /ColorSpace array")),
731 }
732 }
733 _ => Err(Error::malformed("unsupported image /ColorSpace value")),
734 }
735 }
736
737 fn components(&self) -> usize {
738 match self {
739 Self::Gray => 1,
740 Self::Rgb => 3,
741 Self::Cmyk => 4,
742 Self::Indexed { .. } => 1,
743 }
744 }
745}
746
747fn integer(dict: &Dictionary, key: &[u8]) -> Result<u32> {
748 dict.get(key)
749 .and_then(Object::as_integer)
750 .and_then(|value| u32::try_from(value).ok())
751 .ok_or_else(|| Error::malformed("image without integer /Width and /Height"))
752}
753
754fn dict_component_count(stream: &Stream) -> Option<usize> {
757 match stream.dict().get(b"ColorSpace") {
758 Some(Object::Name(name)) if name == b"DeviceCMYK" => Some(4),
759 Some(Object::Name(name)) if name == b"DeviceGray" => Some(1),
760 Some(Object::Name(name)) if name == b"DeviceRGB" => Some(3),
761 _ => None,
762 }
763}
764
765fn widen_one_bit(data: &[u8], width: u32, height: u32, components: usize) -> Result<Vec<u8>> {
770 if components != 1 {
771 return Err(Error::malformed(
772 "one-bit samples need a single-component colour space",
773 ));
774 }
775 let bits_per_row = usize::try_from(width).unwrap_or(0);
776 let stride = bits_per_row.div_ceil(8);
777 let rows = usize::try_from(height).unwrap_or(0);
778 if data.len() < stride.saturating_mul(rows) {
779 return Err(Error::malformed(
780 "one-bit image data is shorter than its rows",
781 ));
782 }
783 let mut out = Vec::with_capacity(bits_per_row.saturating_mul(rows));
784 for row in 0..rows {
785 for column in 0..bits_per_row {
786 let byte = data[row * stride + column / 8];
787 let shift = 7 - column % 8;
788 let bit = (byte >> shift) & 1;
789 out.push(if bit == 1 { 255 } else { 0 });
790 }
791 }
792 Ok(out)
793}
794
795fn has_adobe_marker(data: &[u8]) -> bool {
802 let mut index = 2; while index + 4 <= data.len() {
804 if data[index] != 0xFF {
805 return false;
806 }
807 let marker = data[index + 1];
808 if matches!(marker, 0xD8 | 0x01 | 0xD0..=0xD7) {
810 index += 2;
811 continue;
812 }
813 let length = usize::from(u16::from_be_bytes([data[index + 2], data[index + 3]]));
814 if length < 2 {
815 return false;
816 }
817 if marker == 0xEE {
818 let payload = &data[index + 4..(index + 2 + length).min(data.len())];
819 return payload.starts_with(b"Adobe");
820 }
821 if marker == 0xDA {
823 return false;
824 }
825 index += 2 + length;
826 }
827 false
828}
829
830fn ends_in(dict: &Dictionary, name: &[u8]) -> bool {
832 match dict.get(b"Filter") {
833 Some(Object::Name(filter)) => filter == name,
834 Some(Object::Array(items)) => items
835 .iter()
836 .rev()
837 .find_map(Object::as_name)
838 .is_some_and(|filter| filter == name),
839 _ => false,
840 }
841}
842
843fn is_dct(dict: &Dictionary) -> bool {
845 ends_in(dict, b"DCTDecode")
846}
847
848fn is_jpx(dict: &Dictionary) -> bool {
850 ends_in(dict, b"JPXDecode")
851}
852
853fn is_jbig2(dict: &Dictionary) -> bool {
855 ends_in(dict, b"JBIG2Decode")
856}
857
858pub(crate) fn resolve(document: &Document, object: Option<&Object>) -> Result<Object> {
860 match object {
861 Some(Object::Reference(id)) => document.get_object(*id),
862 Some(other) => Ok(other.clone()),
863 None => Ok(Object::Null),
864 }
865}
866
867#[cfg(feature = "jpx")]
875fn jpx_components(space: &hayro_jpeg2000::ColorSpace) -> Result<usize> {
876 match space {
877 hayro_jpeg2000::ColorSpace::Gray => Ok(1),
878 hayro_jpeg2000::ColorSpace::RGB => Ok(3),
879 hayro_jpeg2000::ColorSpace::CMYK => Ok(4),
880 hayro_jpeg2000::ColorSpace::Icc { .. } => Err(Error::Unsupported {
881 what: "a /JPXDecode image in an ICC colour space",
882 }),
883 hayro_jpeg2000::ColorSpace::Unknown { .. } => Err(Error::Unsupported {
884 what: "a /JPXDecode image in a colour space it cannot name",
885 }),
886 }
887}
888
889#[cfg(feature = "jbig2")]
891fn globals_bytes(document: &Document, dict: &Dictionary) -> Result<Option<Vec<u8>>> {
892 let Some(parms) = dict.get(b"DecodeParms") else {
893 return Ok(None);
894 };
895 let parms = resolve(document, Some(parms))?;
896 let Some(parms) = parms.as_dict() else {
897 return Ok(None);
898 };
899 let Some(globals) = parms.get(b"JBIG2Globals") else {
900 return Ok(None);
901 };
902 let globals = resolve(document, Some(globals))?;
903 let Some(stream) = globals.as_stream() else {
904 return Err(Error::malformed("/JBIG2Globals is not a stream"));
905 };
906 document.decode_stream(stream).map(Some)
907}
908
909#[cfg(feature = "jbig2")]
916struct Rows {
917 packed: Vec<u8>,
918 stride: usize,
921 row: usize,
922 column: usize,
923}
924
925#[cfg(feature = "jbig2")]
926impl Rows {
927 fn new(width: usize, height: usize) -> Self {
928 Self {
929 packed: vec![0; width.div_ceil(8) * height],
930 stride: width.div_ceil(8),
931 row: 0,
932 column: 0,
933 }
934 }
935
936 fn run(&mut self, white: bool, count: usize) {
944 for _ in 0..count {
945 if white {
946 let byte = self.row * self.stride + self.column / 8;
947 let shift = 7 - self.column % 8;
948 if let Some(slot) = self.packed.get_mut(byte) {
949 *slot |= 1 << shift;
950 }
951 }
952 self.column += 1;
953 }
954 }
955
956 fn finish(self) -> Vec<u8> {
957 self.packed
958 }
959}
960
961#[cfg(feature = "jbig2")]
962impl hayro_jbig2::Decoder for Rows {
963 fn push_pixel(&mut self, black: bool) {
964 self.run(!black, 1);
965 }
966
967 fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
968 self.run(!black, 8 * chunk_count as usize);
969 }
970
971 fn next_line(&mut self) {
972 self.row += 1;
973 self.column = 0;
974 }
975}
976
977#[cfg(test)]
978mod tests {
979 use super::Image;
980 use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
981 use crate::geom::Matrix;
982
983 #[cfg(feature = "jpx")]
987 #[test]
988 fn jpx_refuses_the_colour_spaces_it_cannot_paint() {
989 use hayro_jpeg2000::ColorSpace;
990
991 assert_eq!(super::jpx_components(&ColorSpace::Gray).unwrap(), 1);
992 assert_eq!(super::jpx_components(&ColorSpace::RGB).unwrap(), 3);
993 assert_eq!(super::jpx_components(&ColorSpace::CMYK).unwrap(), 4);
994 let icc = super::jpx_components(&ColorSpace::Icc {
995 profile: Vec::new(),
996 num_channels: 3,
997 })
998 .expect_err("an ICC space needs colour management");
999 assert!(icc.to_string().contains("ICC"), "{icc}");
1000 let unknown = super::jpx_components(&ColorSpace::Unknown { num_channels: 2 })
1001 .expect_err("an unnamed space is refused");
1002 assert!(unknown.to_string().contains("cannot name"), "{unknown}");
1003 }
1004
1005 fn image(width: u32, height: u32, interpolate: bool) -> Image {
1006 let mut pixels = Vec::new();
1007 for y in 0..height {
1008 for x in 0..width {
1009 pixels.push(if (x + y) % 2 == 0 {
1010 Color::BLACK
1011 } else {
1012 Color::WHITE
1013 });
1014 }
1015 }
1016 Image {
1017 width,
1018 height,
1019 pixels,
1020 interpolate,
1021 masked: None,
1022 }
1023 }
1024
1025 #[test]
1026 fn nearest_sampling_returns_whole_pixels() {
1027 let image = image(2, 2, false);
1028 assert_eq!(image.sample(0.25, 0.25), Color::BLACK);
1029 assert_eq!(image.sample(0.75, 0.25), Color::WHITE);
1030 assert_eq!(image.sample(0.25, 0.75), Color::WHITE);
1031 }
1032
1033 #[test]
1034 fn bilinear_sampling_blends_neighbours() {
1035 let image = image(2, 2, true);
1036 let middle = image.sample(0.5, 0.5);
1037 assert!((middle.r - 0.5).abs() < 1e-9, "{middle:?}");
1038 }
1039
1040 #[test]
1041 fn painting_covers_the_unit_square_transform() {
1042 let image = image(2, 2, false);
1043 let mut canvas = Canvas::new(4, 4, Color::WHITE);
1044 let mask = ClipMask::all(4, 4);
1045 let ctm = Matrix::new(4.0, 0.0, 0.0, -4.0, 0.0, 4.0);
1047 image.paint(&mut canvas, &mask, ctm, 1.0, BlendMode::Normal);
1048 assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
1049 assert_eq!(canvas.pixel(3, 0), Some([255, 255, 255, 255]));
1050 assert_eq!(canvas.pixel(0, 3), Some([255, 255, 255, 255]));
1051 assert_eq!(canvas.pixel(3, 3), Some([0, 0, 0, 255]));
1052 }
1053}