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 pixels = widened
420 .into_iter()
421 .map(|sample| {
422 let grey = f64::from(sample) / 255.0;
423 Color::rgb(grey, grey, grey)
424 })
425 .collect();
426 Ok(Self {
427 width,
428 height,
429 pixels,
430 interpolate,
431 masked: None,
432 })
433 }
434
435 fn is_masked(&self, u: f64, v: f64) -> bool {
437 let Some(masked) = &self.masked else {
438 return false;
439 };
440 if self.width == 0 || self.height == 0 {
441 return false;
442 }
443 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
444 let x = (u.clamp(0.0, 1.0) * f64::from(self.width)) as u32;
445 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
446 let y = (v.clamp(0.0, 1.0) * f64::from(self.height)) as u32;
447 let x = x.min(self.width - 1);
448 let y = y.min(self.height - 1);
449 masked
450 .get((y * self.width + x) as usize)
451 .copied()
452 .unwrap_or(false)
453 }
454
455 pub fn width(&self) -> u32 {
457 self.width
458 }
459
460 pub fn height(&self) -> u32 {
462 self.height
463 }
464
465 pub fn sample(&self, u: f64, v: f64) -> Color {
467 if self.width == 0 || self.height == 0 {
468 return Color::WHITE;
469 }
470 let x = (u.clamp(0.0, 1.0) * f64::from(self.width) - 0.5).max(0.0);
471 let y = (v.clamp(0.0, 1.0) * f64::from(self.height) - 0.5).max(0.0);
472 if !self.interpolate {
473 return self.pixel(x.round() as u32, y.round() as u32);
474 }
475 let x0 = x.floor() as u32;
476 let y0 = y.floor() as u32;
477 let x1 = (x0 + 1).min(self.width - 1);
478 let y1 = (y0 + 1).min(self.height - 1);
479 let fx = x - f64::from(x0);
480 let fy = y - f64::from(y0);
481 let top = mix(self.pixel(x0, y0), self.pixel(x1, y0), fx);
482 let bottom = mix(self.pixel(x0, y1), self.pixel(x1, y1), fx);
483 mix(top, bottom, fy)
484 }
485
486 fn pixel(&self, x: u32, y: u32) -> Color {
487 let x = x.min(self.width - 1);
488 let y = y.min(self.height - 1);
489 self.pixels[(y as usize) * (self.width as usize) + (x as usize)]
490 }
491
492 pub fn paint(
494 &self,
495 canvas: &mut Canvas,
496 mask: &ClipMask,
497 ctm: Matrix,
498 alpha: f64,
499 mode: BlendMode,
500 ) {
501 let Some(inverse) = ctm.invert() else {
502 return;
503 };
504 let corners = [
505 ctm.apply(Point::new(0.0, 0.0)),
506 ctm.apply(Point::new(1.0, 0.0)),
507 ctm.apply(Point::new(0.0, 1.0)),
508 ctm.apply(Point::new(1.0, 1.0)),
509 ];
510 let min_x = corners
511 .iter()
512 .fold(f64::INFINITY, |min, point| min.min(point.x))
513 .floor()
514 .max(0.0);
515 let max_x = corners
516 .iter()
517 .fold(f64::NEG_INFINITY, |max, point| max.max(point.x))
518 .ceil()
519 .min(f64::from(canvas.width()));
520 let min_y = corners
521 .iter()
522 .fold(f64::INFINITY, |min, point| min.min(point.y))
523 .floor()
524 .max(0.0);
525 let max_y = corners
526 .iter()
527 .fold(f64::NEG_INFINITY, |max, point| max.max(point.y))
528 .ceil()
529 .min(f64::from(canvas.height()));
530 for y in min_y as u32..max_y as u32 {
531 for x in min_x as u32..max_x as u32 {
532 let coverage = mask.alpha(x, y);
533 if coverage <= 0.0 {
534 continue;
535 }
536 let device = Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
537 let user = inverse.apply(device);
538 if !(0.0..=1.0).contains(&user.x) || !(0.0..=1.0).contains(&user.y) {
539 continue;
540 }
541 let v = 1.0 - user.y;
544 if self.is_masked(user.x, v) {
545 continue;
549 }
550 let colour = self.sample(user.x, v);
551 canvas.blend_with(x, y, colour, alpha * coverage, mode);
552 }
553 }
554 }
555}
556
557#[derive(Debug, Clone, PartialEq, Eq)]
563struct ColourKey {
564 min: [u8; 4],
565 max: [u8; 4],
566 components: usize,
567}
568
569impl ColourKey {
570 fn parse(items: &[Object], components: usize, bits: i64) -> Result<Self> {
573 if items.len() != components * 2 {
574 return Err(Error::malformed(
575 "a /Mask whose length is not twice the image's component count",
576 ));
577 }
578 let scale = if bits == 1 { 255.0 } else { 1.0 };
579 let limit = if bits == 1 { 1.0 } else { 255.0 };
580 let mut min = [0_u8; 4];
581 let mut max = [0_u8; 4];
582 for slot in 0..components {
583 let low = items[slot * 2].as_real().unwrap_or(-1.0);
584 let high = items[slot * 2 + 1].as_real().unwrap_or(-1.0);
585 if !(0.0..=limit).contains(&low) || !(0.0..=limit).contains(&high) {
586 return Err(Error::malformed("a /Mask value outside the sample range"));
587 }
588 min[slot] = (low * scale).round() as u8;
589 max[slot] = (high * scale).round() as u8;
590 }
591 Ok(Self {
592 min,
593 max,
594 components,
595 })
596 }
597
598 fn masks(&self, sample: &[u8]) -> bool {
600 sample
601 .iter()
602 .take(self.components)
603 .enumerate()
604 .all(|(slot, byte)| (self.min[slot]..=self.max[slot]).contains(byte))
605 }
606}
607
608fn decode_ranges(decode: Option<&Object>, components: usize) -> Vec<(f64, f64)> {
610 let mut ranges = vec![(0.0, 1.0); components];
611 let Some(Object::Array(items)) = decode else {
612 return ranges;
613 };
614 if items.len() < components * 2 {
615 return ranges;
616 }
617 for (slot, pair) in items.as_chunks::<2>().0.iter().enumerate().take(components) {
618 let (Some(from), Some(to)) = (pair[0].as_real(), pair[1].as_real()) else {
619 continue;
620 };
621 ranges[slot] = (from, to);
622 }
623 ranges
624}
625
626fn colour_at(colours: &ColourSpace, components: &[f64; 4]) -> Color {
628 match colours {
629 ColourSpace::Gray => Color::rgb(components[0], components[0], components[0]),
630 ColourSpace::Rgb => Color::rgb(components[0], components[1], components[2]),
631 ColourSpace::Cmyk => {
632 Color::from_cmyk(components[0], components[1], components[2], components[3])
633 }
634 ColourSpace::Indexed { base, lookup } => {
635 let index = (components[0] * 255.0).round().max(0.0) as usize;
638 let count = base.components();
639 let entry = index * count;
640 let slice = lookup.get(entry..entry + count).unwrap_or(&[]);
641 if slice.len() < count {
642 return Color::BLACK;
643 }
644 let mut table = [0.0_f64; 4];
645 for (slot, byte) in slice.iter().enumerate().take(4) {
646 table[slot] = f64::from(*byte) / 255.0;
647 }
648 colour_at(base, &table)
649 }
650 }
651}
652
653fn mix(left: Color, right: Color, t: f64) -> Color {
654 let t = t.clamp(0.0, 1.0);
655 Color::rgb(
656 left.r * (1.0 - t) + right.r * t,
657 left.g * (1.0 - t) + right.g * t,
658 left.b * (1.0 - t) + right.b * t,
659 )
660}
661
662#[derive(Debug, Clone, PartialEq)]
664enum ColourSpace {
665 Gray,
666 Rgb,
667 Cmyk,
668 Indexed {
669 base: Box<ColourSpace>,
670 lookup: Vec<u8>,
671 },
672}
673
674impl ColourSpace {
675 fn from_object(document: &Document, object: Object) -> Result<Self> {
676 match object {
677 Object::Name(name) => match name.as_slice() {
678 b"DeviceGray" | b"G" | b"CalGray" => Ok(Self::Gray),
679 b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(Self::Rgb),
680 b"DeviceCMYK" | b"CMYK" => Ok(Self::Cmyk),
681 _ => Err(Error::malformed("unsupported image /ColorSpace")),
682 },
683 Object::Array(items) => {
684 let family = match items.first() {
685 Some(Object::Name(name)) => name.clone(),
686 _ => return Err(Error::malformed("image /ColorSpace array family")),
687 };
688 match family.as_slice() {
689 b"Indexed" | b"I" => {
690 let base = match items.get(1) {
691 Some(base) => {
692 Self::from_object(document, resolve(document, Some(base))?)?
693 }
694 None => return Err(Error::malformed("Indexed image without a base")),
695 };
696 let lookup = match items.get(3) {
697 Some(Object::String(string)) => string.as_bytes().to_vec(),
698 Some(Object::Reference(id)) => document.stream_data(*id)?,
699 _ => {
700 return Err(Error::malformed(
701 "Indexed image without a lookup table",
702 ));
703 }
704 };
705 Ok(Self::Indexed {
706 base: Box::new(base),
707 lookup,
708 })
709 }
710 b"ICCBased" => {
711 let stream = match items.get(1) {
712 Some(Object::Reference(id)) => document.stream(*id)?,
713 _ => return Err(Error::malformed("ICCBased without a stream")),
714 };
715 let components = stream
716 .dict()
717 .get(b"N")
718 .and_then(Object::as_integer)
719 .unwrap_or(3);
720 match components {
721 1 => Ok(Self::Gray),
722 3 => Ok(Self::Rgb),
723 4 => Ok(Self::Cmyk),
724 _ => Err(Error::malformed("unsupported ICCBased components")),
725 }
726 }
727 _ => Err(Error::malformed("unsupported image /ColorSpace array")),
728 }
729 }
730 _ => Err(Error::malformed("unsupported image /ColorSpace value")),
731 }
732 }
733
734 fn components(&self) -> usize {
735 match self {
736 Self::Gray => 1,
737 Self::Rgb => 3,
738 Self::Cmyk => 4,
739 Self::Indexed { .. } => 1,
740 }
741 }
742}
743
744fn integer(dict: &Dictionary, key: &[u8]) -> Result<u32> {
745 dict.get(key)
746 .and_then(Object::as_integer)
747 .and_then(|value| u32::try_from(value).ok())
748 .ok_or_else(|| Error::malformed("image without integer /Width and /Height"))
749}
750
751fn dict_component_count(stream: &Stream) -> Option<usize> {
754 match stream.dict().get(b"ColorSpace") {
755 Some(Object::Name(name)) if name == b"DeviceCMYK" => Some(4),
756 Some(Object::Name(name)) if name == b"DeviceGray" => Some(1),
757 Some(Object::Name(name)) if name == b"DeviceRGB" => Some(3),
758 _ => None,
759 }
760}
761
762fn widen_one_bit(data: &[u8], width: u32, height: u32, components: usize) -> Result<Vec<u8>> {
767 if components != 1 {
768 return Err(Error::malformed(
769 "one-bit samples need a single-component colour space",
770 ));
771 }
772 let bits_per_row = usize::try_from(width).unwrap_or(0);
773 let stride = bits_per_row.div_ceil(8);
774 let rows = usize::try_from(height).unwrap_or(0);
775 if data.len() < stride.saturating_mul(rows) {
776 return Err(Error::malformed(
777 "one-bit image data is shorter than its rows",
778 ));
779 }
780 let mut out = Vec::with_capacity(bits_per_row.saturating_mul(rows));
781 for row in 0..rows {
782 for column in 0..bits_per_row {
783 let byte = data[row * stride + column / 8];
784 let shift = 7 - column % 8;
785 let bit = (byte >> shift) & 1;
786 out.push(if bit == 1 { 255 } else { 0 });
787 }
788 }
789 Ok(out)
790}
791
792fn has_adobe_marker(data: &[u8]) -> bool {
799 let mut index = 2; while index + 4 <= data.len() {
801 if data[index] != 0xFF {
802 return false;
803 }
804 let marker = data[index + 1];
805 if matches!(marker, 0xD8 | 0x01 | 0xD0..=0xD7) {
807 index += 2;
808 continue;
809 }
810 let length = usize::from(u16::from_be_bytes([data[index + 2], data[index + 3]]));
811 if length < 2 {
812 return false;
813 }
814 if marker == 0xEE {
815 let payload = &data[index + 4..(index + 2 + length).min(data.len())];
816 return payload.starts_with(b"Adobe");
817 }
818 if marker == 0xDA {
820 return false;
821 }
822 index += 2 + length;
823 }
824 false
825}
826
827fn ends_in(dict: &Dictionary, name: &[u8]) -> bool {
829 match dict.get(b"Filter") {
830 Some(Object::Name(filter)) => filter == name,
831 Some(Object::Array(items)) => items
832 .iter()
833 .rev()
834 .find_map(Object::as_name)
835 .is_some_and(|filter| filter == name),
836 _ => false,
837 }
838}
839
840fn is_dct(dict: &Dictionary) -> bool {
842 ends_in(dict, b"DCTDecode")
843}
844
845fn is_jpx(dict: &Dictionary) -> bool {
847 ends_in(dict, b"JPXDecode")
848}
849
850fn is_jbig2(dict: &Dictionary) -> bool {
852 ends_in(dict, b"JBIG2Decode")
853}
854
855pub(crate) fn resolve(document: &Document, object: Option<&Object>) -> Result<Object> {
857 match object {
858 Some(Object::Reference(id)) => document.get_object(*id),
859 Some(other) => Ok(other.clone()),
860 None => Ok(Object::Null),
861 }
862}
863
864#[cfg(feature = "jpx")]
872fn jpx_components(space: &hayro_jpeg2000::ColorSpace) -> Result<usize> {
873 match space {
874 hayro_jpeg2000::ColorSpace::Gray => Ok(1),
875 hayro_jpeg2000::ColorSpace::RGB => Ok(3),
876 hayro_jpeg2000::ColorSpace::CMYK => Ok(4),
877 hayro_jpeg2000::ColorSpace::Icc { .. } => Err(Error::Unsupported {
878 what: "a /JPXDecode image in an ICC colour space",
879 }),
880 hayro_jpeg2000::ColorSpace::Unknown { .. } => Err(Error::Unsupported {
881 what: "a /JPXDecode image in a colour space it cannot name",
882 }),
883 }
884}
885
886#[cfg(feature = "jbig2")]
888fn globals_bytes(document: &Document, dict: &Dictionary) -> Result<Option<Vec<u8>>> {
889 let Some(parms) = dict.get(b"DecodeParms") else {
890 return Ok(None);
891 };
892 let parms = resolve(document, Some(parms))?;
893 let Some(parms) = parms.as_dict() else {
894 return Ok(None);
895 };
896 let Some(globals) = parms.get(b"JBIG2Globals") else {
897 return Ok(None);
898 };
899 let globals = resolve(document, Some(globals))?;
900 let Some(stream) = globals.as_stream() else {
901 return Err(Error::malformed("/JBIG2Globals is not a stream"));
902 };
903 document.decode_stream(stream).map(Some)
904}
905
906#[cfg(feature = "jbig2")]
913struct Rows {
914 packed: Vec<u8>,
915 stride: usize,
918 row: usize,
919 column: usize,
920}
921
922#[cfg(feature = "jbig2")]
923impl Rows {
924 fn new(width: usize, height: usize) -> Self {
925 Self {
926 packed: vec![0; width.div_ceil(8) * height],
927 stride: width.div_ceil(8),
928 row: 0,
929 column: 0,
930 }
931 }
932
933 fn run(&mut self, white: bool, count: usize) {
941 for _ in 0..count {
942 if white {
943 let byte = self.row * self.stride + self.column / 8;
944 let shift = 7 - self.column % 8;
945 if let Some(slot) = self.packed.get_mut(byte) {
946 *slot |= 1 << shift;
947 }
948 }
949 self.column += 1;
950 }
951 }
952
953 fn finish(self) -> Vec<u8> {
954 self.packed
955 }
956}
957
958#[cfg(feature = "jbig2")]
959impl hayro_jbig2::Decoder for Rows {
960 fn push_pixel(&mut self, black: bool) {
961 self.run(!black, 1);
962 }
963
964 fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
965 self.run(!black, 8 * chunk_count as usize);
966 }
967
968 fn next_line(&mut self) {
969 self.row += 1;
970 self.column = 0;
971 }
972}
973
974#[cfg(test)]
975mod tests {
976 use super::Image;
977 use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
978 use crate::geom::Matrix;
979
980 #[cfg(feature = "jpx")]
984 #[test]
985 fn jpx_refuses_the_colour_spaces_it_cannot_paint() {
986 use hayro_jpeg2000::ColorSpace;
987
988 assert_eq!(super::jpx_components(&ColorSpace::Gray).unwrap(), 1);
989 assert_eq!(super::jpx_components(&ColorSpace::RGB).unwrap(), 3);
990 assert_eq!(super::jpx_components(&ColorSpace::CMYK).unwrap(), 4);
991 let icc = super::jpx_components(&ColorSpace::Icc {
992 profile: Vec::new(),
993 num_channels: 3,
994 })
995 .expect_err("an ICC space needs colour management");
996 assert!(icc.to_string().contains("ICC"), "{icc}");
997 let unknown = super::jpx_components(&ColorSpace::Unknown { num_channels: 2 })
998 .expect_err("an unnamed space is refused");
999 assert!(unknown.to_string().contains("cannot name"), "{unknown}");
1000 }
1001
1002 fn image(width: u32, height: u32, interpolate: bool) -> Image {
1003 let mut pixels = Vec::new();
1004 for y in 0..height {
1005 for x in 0..width {
1006 pixels.push(if (x + y) % 2 == 0 {
1007 Color::BLACK
1008 } else {
1009 Color::WHITE
1010 });
1011 }
1012 }
1013 Image {
1014 width,
1015 height,
1016 pixels,
1017 interpolate,
1018 masked: None,
1019 }
1020 }
1021
1022 #[test]
1023 fn nearest_sampling_returns_whole_pixels() {
1024 let image = image(2, 2, false);
1025 assert_eq!(image.sample(0.25, 0.25), Color::BLACK);
1026 assert_eq!(image.sample(0.75, 0.25), Color::WHITE);
1027 assert_eq!(image.sample(0.25, 0.75), Color::WHITE);
1028 }
1029
1030 #[test]
1031 fn bilinear_sampling_blends_neighbours() {
1032 let image = image(2, 2, true);
1033 let middle = image.sample(0.5, 0.5);
1034 assert!((middle.r - 0.5).abs() < 1e-9, "{middle:?}");
1035 }
1036
1037 #[test]
1038 fn painting_covers_the_unit_square_transform() {
1039 let image = image(2, 2, false);
1040 let mut canvas = Canvas::new(4, 4, Color::WHITE);
1041 let mask = ClipMask::all(4, 4);
1042 let ctm = Matrix::new(4.0, 0.0, 0.0, -4.0, 0.0, 4.0);
1044 image.paint(&mut canvas, &mask, ctm, 1.0, BlendMode::Normal);
1045 assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
1046 assert_eq!(canvas.pixel(3, 0), Some([255, 255, 255, 255]));
1047 assert_eq!(canvas.pixel(0, 3), Some([255, 255, 255, 255]));
1048 assert_eq!(canvas.pixel(3, 3), Some([0, 0, 0, 255]));
1049 }
1050}