1use crate::common::include::guiddef::GUID;
2use crate::image::sys::strcodec::{create_ws_file_owned, WsFileMode};
3use crate::image::sys::windowsmediaphoto::{tagCWMIStrCodecParam, tagCWMTranscodingParam};
4use crate::jxrgluelib::jxrglue::{
5 pixel_format_lookup, pk_codec_factory_create_decoder_from_file, tagPKImageDecode,
6 tagPKPixelInfo, tagPKRect, BitDepth as JxrBitDepth, ColorFormat as JxrColorFormat,
7 GUID_PKPixelFormatDontCare, PixelFormatFlags, PixelFormatInterpretation as JxrInterpretation,
8 LOOKUP_FORWARD,
9};
10use crate::jxrgluelib::jxrglue_jxr::pk_image_encode_create_wmp_owned;
11use crate::WmpError;
12use std::fs::File;
13use std::io::{Read, Write};
14use std::path::{Path, PathBuf};
15
16pub type Result<T> = std::result::Result<T, Error>;
17
18#[derive(Debug)]
19pub enum Error {
20 Codec(WmpError),
21 Io(std::io::Error),
22 InvalidPixelFormat,
23 InvalidDimensions,
24 InvalidStride,
25 BufferTooSmall,
26 SizeOverflow,
27}
28
29impl std::fmt::Display for Error {
30 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31 match self {
32 Error::Codec(err) => write!(f, "JPEG-XR codec error: {err}"),
33 Error::Io(err) => write!(f, "I/O error: {err}"),
34 Error::InvalidPixelFormat => f.write_str("invalid JPEG-XR pixel format"),
35 Error::InvalidDimensions => f.write_str("invalid image dimensions"),
36 Error::InvalidStride => f.write_str("invalid image stride"),
37 Error::BufferTooSmall => f.write_str("pixel buffer is too small"),
38 Error::SizeOverflow => f.write_str("image size overflows addressable memory"),
39 }
40 }
41}
42
43impl std::error::Error for Error {}
44
45impl From<WmpError> for Error {
46 fn from(value: WmpError) -> Self {
47 Error::Codec(value)
48 }
49}
50
51impl From<std::io::Error> for Error {
52 fn from(value: std::io::Error) -> Self {
53 Error::Io(value)
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct PixelFormat {
59 guid: GUID,
60 bits_per_pixel: usize,
61 channel_count: u8,
62 bits_per_sample: u8,
63 sample_count: u8,
64 sample_format: SampleFormat,
65 bit_depth: BitDepth,
66 color_format: ColorFormat,
67 interpretation: PixelInterpretation,
68 channel_order: ChannelOrder,
69 has_alpha: bool,
70 premultiplied_alpha: bool,
71}
72
73impl PixelFormat {
74 pub fn bits_per_pixel(self) -> usize {
75 self.bits_per_pixel
76 }
77
78 pub fn bytes_per_pixel(self) -> usize {
79 self.bits_per_pixel.div_ceil(8)
80 }
81
82 pub fn minimum_stride(self, width: u32) -> Result<usize> {
83 checked_stride(width, self)
84 }
85
86 pub fn channel_count(self) -> u8 {
87 self.channel_count
88 }
89
90 pub fn bits_per_sample(self) -> u8 {
91 self.bits_per_sample
92 }
93
94 pub fn sample_count(self) -> u8 {
95 self.sample_count
96 }
97
98 pub fn sample_format(self) -> SampleFormat {
99 self.sample_format
100 }
101
102 pub fn bit_depth(self) -> BitDepth {
103 self.bit_depth
104 }
105
106 pub fn color_format(self) -> ColorFormat {
107 self.color_format
108 }
109
110 pub fn interpretation(self) -> PixelInterpretation {
111 self.interpretation
112 }
113
114 pub fn channel_order(self) -> ChannelOrder {
115 self.channel_order
116 }
117
118 pub fn has_alpha(self) -> bool {
119 self.has_alpha
120 }
121
122 pub fn premultiplied_alpha(self) -> bool {
123 self.premultiplied_alpha
124 }
125
126 pub fn is_bgr_order(self) -> bool {
127 self.channel_order == ChannelOrder::Bgr
128 }
129
130 fn from_guid(guid: GUID) -> Result<Self> {
131 let mut info = tagPKPixelInfo {
132 pGUIDPixFmt: Some(guid),
133 cChannel: 0,
134 cfColorFormat: JxrColorFormat::YOnly,
135 bdBitDepth: JxrBitDepth::One,
136 cbitUnit: 0,
137 grBit: PixelFormatFlags::NONE,
138 uInterpretation: JxrInterpretation::WhiteIsZero,
139 uSamplePerPixel: 0,
140 uBitsPerSample: 0,
141 uSampleFormat: 0,
142 };
143 unsafe {
144 pixel_format_lookup(&mut info, LOOKUP_FORWARD)?;
145 }
146 if info.pGUIDPixFmt == Some(GUID_PKPixelFormatDontCare) || info.cbitUnit == 0 {
147 return Err(Error::InvalidPixelFormat);
148 }
149 Ok(Self {
150 guid,
151 bits_per_pixel: info.cbitUnit as usize,
152 channel_count: info
153 .cChannel
154 .try_into()
155 .map_err(|_| Error::InvalidPixelFormat)?,
156 bits_per_sample: info
157 .uBitsPerSample
158 .try_into()
159 .map_err(|_| Error::InvalidPixelFormat)?,
160 sample_count: info
161 .uSamplePerPixel
162 .try_into()
163 .map_err(|_| Error::InvalidPixelFormat)?,
164 sample_format: SampleFormat::from_jxr(info.uSampleFormat),
165 bit_depth: BitDepth::from_jxr(info.bdBitDepth),
166 color_format: ColorFormat::from_jxr(info.cfColorFormat),
167 interpretation: PixelInterpretation::from_jxr(info.uInterpretation),
168 channel_order: if (info.grBit & PixelFormatFlags::BGR) == PixelFormatFlags::BGR {
169 ChannelOrder::Bgr
170 } else if info.uInterpretation == JxrInterpretation::Rgb {
171 ChannelOrder::Rgb
172 } else {
173 ChannelOrder::Unspecified
174 },
175 has_alpha: (info.grBit & PixelFormatFlags::HAS_ALPHA) == PixelFormatFlags::HAS_ALPHA,
176 premultiplied_alpha: (info.grBit & PixelFormatFlags::PRE_MULTIPLIED)
177 == PixelFormatFlags::PRE_MULTIPLIED,
178 })
179 }
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum ChannelOrder {
184 Unspecified,
185 Rgb,
186 Bgr,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum ColorFormat {
191 Luma,
192 Yuv420,
193 Yuv422,
194 Yuv444,
195 Cmyk,
196 NComponent,
197 Rgb,
198 Rgbe,
199 Other,
200}
201
202impl ColorFormat {
203 fn from_jxr(value: JxrColorFormat) -> Self {
204 match value {
205 JxrColorFormat::YOnly => Self::Luma,
206 JxrColorFormat::Yuv420 => Self::Yuv420,
207 JxrColorFormat::Yuv422 => Self::Yuv422,
208 JxrColorFormat::Yuv444 => Self::Yuv444,
209 JxrColorFormat::Cmyk => Self::Cmyk,
210 JxrColorFormat::NComponent => Self::NComponent,
211 JxrColorFormat::Rgb => Self::Rgb,
212 JxrColorFormat::Rgbe => Self::Rgbe,
213 JxrColorFormat::Max => Self::Other,
214 }
215 }
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum BitDepth {
220 One,
221 Eight,
222 Sixteen,
223 SignedSixteen,
224 HalfFloat,
225 ThirtyTwo,
226 SignedThirtyTwo,
227 Float,
228 Five,
229 Ten,
230 FiveSixFive,
231 Other,
232}
233
234impl BitDepth {
235 fn from_jxr(value: JxrBitDepth) -> Self {
236 match value {
237 JxrBitDepth::One | JxrBitDepth::OneAlt => Self::One,
238 JxrBitDepth::Eight => Self::Eight,
239 JxrBitDepth::Sixteen => Self::Sixteen,
240 JxrBitDepth::SixteenS => Self::SignedSixteen,
241 JxrBitDepth::SixteenF => Self::HalfFloat,
242 JxrBitDepth::ThirtyTwo => Self::ThirtyTwo,
243 JxrBitDepth::ThirtyTwoS => Self::SignedThirtyTwo,
244 JxrBitDepth::ThirtyTwoF => Self::Float,
245 JxrBitDepth::Five => Self::Five,
246 JxrBitDepth::Ten => Self::Ten,
247 JxrBitDepth::FiveSixFive => Self::FiveSixFive,
248 }
249 }
250}
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub enum PixelInterpretation {
254 WhiteIsZero,
255 BlackIsZero,
256 Rgb,
257 Cmyk,
258 NChannel,
259 Rgbe,
260 Other,
261}
262
263impl PixelInterpretation {
264 fn from_jxr(value: JxrInterpretation) -> Self {
265 match value {
266 JxrInterpretation::WhiteIsZero => Self::WhiteIsZero,
267 JxrInterpretation::BlackIsZero => Self::BlackIsZero,
268 JxrInterpretation::Rgb => Self::Rgb,
269 JxrInterpretation::Cmyk => Self::Cmyk,
270 JxrInterpretation::NChannel => Self::NChannel,
271 JxrInterpretation::Rgbe => Self::Rgbe,
272 }
273 }
274}
275
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum SampleFormat {
278 Unspecified,
279 UnsignedInteger,
280 FixedPoint,
281 FloatingPoint,
282 Other(u32),
283}
284
285impl SampleFormat {
286 fn from_jxr(value: u32) -> Self {
287 match value {
288 0 => Self::Unspecified,
289 1 => Self::UnsignedInteger,
290 2 => Self::FixedPoint,
291 3 => Self::FloatingPoint,
292 other => Self::Other(other),
293 }
294 }
295}
296
297#[derive(Debug, Clone)]
298pub struct DecodedImage {
299 width: u32,
300 height: u32,
301 pixel_format: PixelFormat,
302 stride: usize,
303 pixels: Vec<u8>,
304}
305
306impl DecodedImage {
307 pub fn width(&self) -> u32 {
308 self.width
309 }
310
311 pub fn height(&self) -> u32 {
312 self.height
313 }
314
315 pub fn dimensions(&self) -> (u32, u32) {
316 (self.width, self.height)
317 }
318
319 pub fn pixel_format(&self) -> PixelFormat {
320 self.pixel_format
321 }
322
323 pub fn stride(&self) -> usize {
324 self.stride
325 }
326
327 pub fn pixels(&self) -> &[u8] {
328 &self.pixels
329 }
330
331 pub fn into_pixels(self) -> Vec<u8> {
332 self.pixels
333 }
334}
335
336pub struct Decoder {
337 decoder: Box<tagPKImageDecode>,
338 _input: DecoderInput,
339}
340
341enum DecoderInput {
342 File,
343 TempFile(PathBuf),
344}
345
346impl Decoder {
347 pub fn from_slice(data: &[u8]) -> Result<Self> {
354 let path = temp_jxr_path("input");
355 std::fs::write(&path, data)?;
356 let decoder = create_decoder_from_path(&path)?;
357 Ok(Self {
358 decoder,
359 _input: DecoderInput::TempFile(path),
360 })
361 }
362
363 pub fn dimensions(&mut self) -> Result<(u32, u32)> {
364 let mut width = 0;
365 let mut height = 0;
366 unsafe {
367 let get_size = self.decoder.GetSize.ok_or(WmpError::AbstractMethod)?;
368 get_size(&mut *self.decoder, Some(&mut width), Some(&mut height))?;
369 }
370 if width <= 0 || height <= 0 {
371 return Err(Error::InvalidDimensions);
372 }
373 Ok((width as u32, height as u32))
374 }
375
376 pub fn pixel_format(&mut self) -> Result<PixelFormat> {
377 let mut guid = GUID_PKPixelFormatDontCare;
378 unsafe {
379 let get_pixel_format = self
380 .decoder
381 .GetPixelFormat
382 .ok_or(WmpError::AbstractMethod)?;
383 get_pixel_format(&mut *self.decoder, Some(&mut guid))?;
384 }
385 PixelFormat::from_guid(guid)
386 }
387
388 pub fn decode(&mut self) -> Result<DecodedImage> {
389 let (width, height) = self.dimensions()?;
390 let pixel_format = self.pixel_format()?;
391 let stride = checked_stride(width, pixel_format)?;
392 let len = checked_len(stride, height)?;
393 let mut pixels = vec![0; len];
394 self.decode_into(&mut pixels, stride)?;
395 Ok(DecodedImage {
396 width,
397 height,
398 pixel_format,
399 stride,
400 pixels,
401 })
402 }
403
404 pub fn decode_into(&mut self, pixels: &mut [u8], stride: usize) -> Result<()> {
405 let (width, height) = self.dimensions()?;
406 let pixel_format = self.pixel_format()?;
407 validate_pixel_buffer(width, height, pixel_format, pixels.len(), stride)?;
408 let rect = tagPKRect {
409 X: 0,
410 Y: 0,
411 Width: width as i32,
412 Height: height as i32,
413 };
414 unsafe {
415 let copy = self.decoder.Copy.ok_or(WmpError::AbstractMethod)?;
416 copy(&mut *self.decoder, Some(&rect), pixels, stride as u32)?;
417 }
418 Ok(())
419 }
420 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
422 let decoder = create_decoder_from_path(path.as_ref())?;
423 Ok(Self {
424 decoder,
425 _input: DecoderInput::File,
426 })
427 }
428
429 pub fn from_reader(mut reader: impl Read) -> Result<Self> {
431 let mut input = Vec::new();
432 reader.read_to_end(&mut input)?;
433 Self::from_bytes(input)
434 }
435
436 pub fn from_bytes(input: Vec<u8>) -> Result<Self> {
440 let path = temp_jxr_path("input");
441 std::fs::write(&path, &input)?;
442 let decoder = create_decoder_from_path(&path)?;
443 Ok(Self {
444 decoder,
445 _input: DecoderInput::TempFile(path),
446 })
447 }
448}
449
450impl Drop for Decoder {
451 fn drop(&mut self) {
452 if let DecoderInput::TempFile(path) = &self._input {
453 let _ = std::fs::remove_file(path);
454 }
455 }
456}
457
458pub struct Encoder {
459 options: EncoderOptions,
460}
461
462#[derive(Debug, Clone)]
463pub struct EncoderOptions {
464 pub color_format: EncoderColorFormat,
465}
466
467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
468pub enum EncoderColorFormat {
469 Yuv444,
470}
471
472impl Default for EncoderOptions {
473 fn default() -> Self {
474 Self {
475 color_format: EncoderColorFormat::Yuv444,
476 }
477 }
478}
479
480impl Default for Encoder {
481 fn default() -> Self {
482 Self::new()
483 }
484}
485
486impl Encoder {
487 pub fn new() -> Self {
488 Self {
489 options: EncoderOptions::default(),
490 }
491 }
492
493 pub fn with_options(options: EncoderOptions) -> Self {
494 Self { options }
495 }
496
497 pub fn encode_image_to_path(&self, image: &DecodedImage, path: impl AsRef<Path>) -> Result<()> {
498 self.encode_pixels_to_path(
499 image.width,
500 image.height,
501 image.pixel_format,
502 image.pixels(),
503 image.stride,
504 path,
505 )
506 }
507
508 pub fn encode_image_to_writer(&self, image: &DecodedImage, writer: impl Write) -> Result<()> {
509 self.encode_pixels_to_writer(
510 image.width,
511 image.height,
512 image.pixel_format,
513 image.pixels(),
514 image.stride,
515 writer,
516 )
517 }
518
519 pub fn encode_image_to_vec(&self, image: &DecodedImage) -> Result<Vec<u8>> {
520 let mut output = Vec::new();
521 self.encode_image_to_writer(image, &mut output)?;
522 Ok(output)
523 }
524
525 pub fn encode_pixels_to_writer(
526 &self,
527 width: u32,
528 height: u32,
529 pixel_format: PixelFormat,
530 pixels: &[u8],
531 stride: usize,
532 mut writer: impl Write,
533 ) -> Result<()> {
534 let path = temp_jxr_path("encode");
535 let result = (|| {
536 self.encode_pixels_to_path(width, height, pixel_format, pixels, stride, &path)?;
537 let mut file = File::open(&path)?;
538 std::io::copy(&mut file, &mut writer)?;
539 Ok(())
540 })();
541 let _ = std::fs::remove_file(&path);
542 result
543 }
544
545 pub fn encode_pixels_to_path(
546 &self,
547 width: u32,
548 height: u32,
549 pixel_format: PixelFormat,
550 pixels: &[u8],
551 stride: usize,
552 path: impl AsRef<Path>,
553 ) -> Result<()> {
554 validate_pixel_buffer(width, height, pixel_format, pixels.len(), stride)?;
555 unsafe {
556 let mut stream = create_ws_file_owned(path.as_ref(), WsFileMode::ReadWriteTruncate)?;
557 let mut encoder = pk_image_encode_create_wmp_owned();
558 let params = tagCWMIStrCodecParam {
559 cfColorFormat: match self.options.color_format {
560 EncoderColorFormat::Yuv444 => JxrColorFormat::Yuv444,
561 },
562 ..tagCWMIStrCodecParam::default()
563 };
564 let initialize = encoder.Initialize.ok_or(WmpError::AbstractMethod)?;
565 initialize(
566 &mut *encoder,
567 &mut *stream,
568 Some(¶ms),
569 std::mem::size_of::<tagCWMIStrCodecParam>(),
570 )?;
571 let set_pixel_format = encoder.SetPixelFormat.ok_or(WmpError::AbstractMethod)?;
572 set_pixel_format(&mut *encoder, pixel_format.guid)?;
573 let set_size = encoder.SetSize.ok_or(WmpError::AbstractMethod)?;
574 set_size(&mut *encoder, width as i32, height as i32)?;
575 let write_pixels = encoder.WritePixels.ok_or(WmpError::AbstractMethod)?;
576 write_pixels(&mut *encoder, height, pixels, stride as u32)?;
577 drop(encoder);
578 drop(stream);
579 }
580 Ok(())
581 }
582}
583
584pub fn decode_file(path: impl AsRef<Path>) -> Result<DecodedImage> {
585 Decoder::open(path)?.decode()
586}
587
588pub fn decode_reader(reader: impl Read) -> Result<DecodedImage> {
589 Decoder::from_reader(reader)?.decode()
590}
591
592pub fn decode_bytes(data: &[u8]) -> Result<DecodedImage> {
594 Decoder::from_slice(data)?.decode()
595}
596
597pub fn encode_to_writer(image: &DecodedImage, writer: impl Write) -> Result<()> {
598 Encoder::new().encode_image_to_writer(image, writer)
599}
600
601pub fn encode_to_vec(image: &DecodedImage) -> Result<Vec<u8>> {
602 Encoder::new().encode_image_to_vec(image)
603}
604
605pub fn encode_to_path(image: &DecodedImage, path: impl AsRef<Path>) -> Result<()> {
606 Encoder::new().encode_image_to_path(image, path)
607}
608
609pub fn transcode_file_to_path(input: impl AsRef<Path>, output: impl AsRef<Path>) -> Result<()> {
610 let mut bytes = Vec::new();
611 File::open(input)?.read_to_end(&mut bytes)?;
612 transcode_bytes_to_path(bytes, output)
613}
614
615pub fn transcode_reader_to_writer(reader: impl Read, writer: impl Write) -> Result<()> {
616 let mut decoder = Decoder::from_reader(reader)?;
617 transcode_decoder_to_writer(&mut decoder, writer)
618}
619
620pub fn transcode_bytes_to_vec(data: &[u8]) -> Result<Vec<u8>> {
621 let mut decoder = Decoder::from_slice(data)?;
622 let mut output = Vec::new();
623 transcode_decoder_to_writer(&mut decoder, &mut output)?;
624 Ok(output)
625}
626
627pub fn transcode_bytes_to_path(input: Vec<u8>, output: impl AsRef<Path>) -> Result<()> {
628 let mut decoder = Decoder::from_bytes(input)?;
629 transcode_decoder_to_path(&mut decoder, output)
630}
631
632fn transcode_decoder_to_writer(decoder: &mut Decoder, mut writer: impl Write) -> Result<()> {
633 let path = temp_jxr_path("transcode");
634 let result = (|| {
635 transcode_decoder_to_path(decoder, &path)?;
636 let mut file = File::open(&path)?;
637 std::io::copy(&mut file, &mut writer)?;
638 Ok(())
639 })();
640 let _ = std::fs::remove_file(&path);
641 result
642}
643
644fn transcode_decoder_to_path(decoder: &mut Decoder, output: impl AsRef<Path>) -> Result<()> {
645 let (width, height) = decoder.dimensions()?;
646 unsafe {
647 let mut stream = create_ws_file_owned(output.as_ref(), WsFileMode::ReadWriteTruncate)?;
648 let mut encoder = pk_image_encode_create_wmp_owned();
649 let params = tagCWMIStrCodecParam::default();
650 let initialize = encoder.Initialize.ok_or(WmpError::AbstractMethod)?;
651 initialize(
652 &mut *encoder,
653 &mut *stream,
654 Some(¶ms),
655 std::mem::size_of::<tagCWMIStrCodecParam>(),
656 )?;
657
658 let mut transcode = tagCWMTranscodingParam {
659 cLeftX: 0,
660 cWidth: width as usize,
661 cTopY: 0,
662 cHeight: height as usize,
663 bfBitstreamFormat: decoder.decoder.WMP.wmiSCP.bfBitstreamFormat,
664 uAlphaMode: decoder.decoder.WMP.wmiSCP.uAlphaMode,
665 sbSubband: decoder.decoder.WMP.wmiSCP.sbSubband,
666 oOrientation: decoder.decoder.WMP.wmiI.oOrientation,
667 bIgnoreOverlap: decoder.decoder.WMP.bIgnoreOverlap,
668 };
669 let transcode_fn = encoder.Transcode.ok_or(WmpError::AbstractMethod)?;
670 transcode_fn(&mut *encoder, &mut *decoder.decoder, &mut transcode)?;
671 drop(encoder);
672 drop(stream);
673 }
674 Ok(())
675}
676
677fn create_decoder_from_path(path: &Path) -> Result<Box<tagPKImageDecode>> {
678 unsafe { pk_codec_factory_create_decoder_from_file(Some(path)).map_err(Error::from) }
679}
680
681fn checked_stride(width: u32, pixel_format: PixelFormat) -> Result<usize> {
682 (width as usize)
683 .checked_mul(pixel_format.bits_per_pixel())
684 .and_then(|bits| bits.checked_add(7))
685 .map(|bits| bits / 8)
686 .ok_or(Error::SizeOverflow)
687}
688
689fn checked_len(stride: usize, height: u32) -> Result<usize> {
690 stride
691 .checked_mul(height as usize)
692 .ok_or(Error::SizeOverflow)
693}
694
695fn validate_pixel_buffer(
696 width: u32,
697 height: u32,
698 pixel_format: PixelFormat,
699 buffer_len: usize,
700 stride: usize,
701) -> Result<()> {
702 if width == 0 || height == 0 {
703 return Err(Error::InvalidDimensions);
704 }
705 let min_stride = checked_stride(width, pixel_format)?;
706 if stride < min_stride || stride > u32::MAX as usize {
707 return Err(Error::InvalidStride);
708 }
709 let min_len = checked_len(stride, height)?;
710 if buffer_len < min_len {
711 return Err(Error::BufferTooSmall);
712 }
713 Ok(())
714}
715
716fn temp_jxr_path(label: &str) -> PathBuf {
717 let mut path = std::env::temp_dir();
718 path.push(format!(
719 "jpegxr-pure-rs-{label}-{}-{}.jxr",
720 std::process::id(),
721 next_temp_id()
722 ));
723 path
724}
725
726fn next_temp_id() -> u64 {
727 use std::sync::atomic::{AtomicU64, Ordering};
728 static NEXT: AtomicU64 = AtomicU64::new(0);
729 NEXT.fetch_add(1, Ordering::Relaxed)
730}