1use std::io::Cursor;
12use std::sync::Arc;
13
14use alpha2_model::{LinearPrimaries, ProviderSource};
15use alpha2_time::MediaTime;
16use exr::block::reader::ChunksReader as _;
17use exr::meta::BlockDescription;
18use exr::meta::attribute::{ChannelDescription, ChannelList, SampleType};
19use half::f16;
20use half::slice::{HalfBitsSliceExt as _, HalfFloatSliceExt as _};
21
22use crate::api::{
23 ColorOrigin, Diagnostic, ExtensionError, Format, FramePixels, LinearColor, ProbeReport,
24 ResourceResolver, Timing, VisualFrame, VisualProvider, VisualSource,
25};
26use crate::budget::{MAX_CANVAS_PIXELS, check_canvas};
27
28const MAGIC: [u8; 4] = [0x76, 0x2f, 0x31, 0x01];
29
30pub(crate) const MAX_EXR_BLOCK_BYTES: u64 = 256 << 20;
33
34pub(crate) fn is_exr(bytes: &[u8]) -> bool {
35 bytes.starts_with(&MAGIC)
36}
37
38pub struct ExrProvider;
40
41impl VisualProvider for ExrProvider {
42 fn name(&self) -> &'static str {
43 "exr"
44 }
45
46 fn probe(&self, bytes: &[u8]) -> Option<Result<ProbeReport, ExtensionError>> {
47 is_exr(bytes).then(|| decode_exr(bytes, None).map(|image| still_report(&image)))
48 }
49
50 fn open(
51 &self,
52 bytes: Arc<[u8]>,
53 source: &ProviderSource,
54 _resolver: &dyn ResourceResolver,
55 ) -> Result<Box<dyn VisualSource>, ExtensionError> {
56 let ProviderSource::Exr { primaries } = source else {
57 return Err(ExtensionError::Mismatch("not an OpenEXR source".into()));
58 };
59 if !is_exr(&bytes) {
60 return Err(ExtensionError::Mismatch("not an OpenEXR file".into()));
61 }
62 let image = decode_exr(&bytes, primaries.map(project_color))?;
63 let report = still_report(&image);
64 Ok(Box::new(ExrSource {
65 report,
66 frame: VisualFrame {
67 width: image.width,
68 height: image.height,
69 pixels: FramePixels::LinearF16(image.pixels),
70 index: 0,
71 start: MediaTime::from_ticks(i64::MIN),
72 end: None,
73 diagnostics: Vec::new(),
74 },
75 }))
76 }
77}
78
79fn still_report(image: &ExrImage) -> ProbeReport {
80 ProbeReport {
81 format: Format::Exr,
82 width: image.width,
83 height: image.height,
84 timing: Timing::Static,
85 loop_count: None,
86 items: Vec::new(),
87 item: None,
88 color: Some(image.color.clone()),
89 diagnostics: image.diagnostics.clone(),
90 }
91}
92
93struct ExrSource {
94 report: ProbeReport,
95 frame: VisualFrame,
96}
97
98impl VisualSource for ExrSource {
99 fn report(&self) -> &ProbeReport {
100 &self.report
101 }
102
103 fn render(
104 &mut self,
105 _time: MediaTime,
106 _fit: (u32, u32),
107 ) -> Result<VisualFrame, ExtensionError> {
108 Ok(self.frame.clone())
109 }
110
111 fn resident_bytes(&self) -> usize {
112 self.frame.pixels.byte_len()
113 }
114}
115
116pub(crate) struct ExrImage {
117 pub(crate) width: u32,
118 pub(crate) height: u32,
119 pub(crate) pixels: Arc<[u16]>,
121 pub(crate) color: LinearColor,
122 pub(crate) diagnostics: Vec<Diagnostic>,
123}
124
125pub(crate) fn project_color(primaries: LinearPrimaries) -> LinearColor {
126 LinearColor {
127 primaries: Some(primaries),
128 chromaticities: named_chromaticities(primaries),
129 origin: ColorOrigin::Project,
130 }
131}
132
133pub(crate) fn decode_exr(
136 bytes: &[u8],
137 color: Option<LinearColor>,
138) -> Result<ExrImage, ExtensionError> {
139 check_channel_lists(bytes)?;
140 let reader = exr::block::read(Cursor::new(bytes), false).map_err(exr_error)?;
141 let headers = reader.headers();
142 if headers.iter().all(|header| header.deep) {
143 return Err(ExtensionError::Unsupported(
144 "deep OpenEXR data is not supported".into(),
145 ));
146 }
147 check_block_bytes(headers)?;
148 let Some(part) = headers.iter().position(|header| {
149 !header.deep
150 && channels_shown(header.channels.list.iter().map(|c| c.name.to_string())).is_some()
151 }) else {
152 let names = headers
153 .iter()
154 .flat_map(|header| {
155 header
156 .channels
157 .list
158 .iter()
159 .map(|channel| channel.name.to_string())
160 })
161 .collect::<Vec<_>>()
162 .join(", ");
163 return Err(ExtensionError::Unsupported(format!(
164 "no part has R, G, and B channels or a Y channel (it has {names})"
165 )));
166 };
167 let header = headers[part].clone();
168 let display = header.shared_attributes.display_window;
169 let (width, height) = (
170 u32::try_from(display.size.x()).unwrap_or(u32::MAX),
171 u32::try_from(display.size.y()).unwrap_or(u32::MAX),
172 );
173 let mut diagnostics = check_part(&header, width, height, part, headers.len())?;
174 let color = color.unwrap_or_else(|| {
175 let declared = file_color(header.shared_attributes.chromaticities);
176 if defines_color_space(declared.chromaticities) {
177 return declared;
178 }
179 diagnostics.push(Diagnostic::UnsupportedFeature {
181 feature: "chromaticities that define no color space".into(),
182 path: "/chromaticities".into(),
183 count: 1,
184 });
185 file_color(None)
186 });
187
188 let channels = &header.channels.list;
189 let shown = channels_shown(channels.iter().map(|channel| channel.name.to_string()))
190 .ok_or_else(|| ExtensionError::Malformed("the part's channels could not be read".into()))?;
191 let others = (0..channels.len())
192 .filter(|index| !shown.contains(&Some(*index)))
193 .collect::<Vec<_>>();
194 if let Some(first) = others.first() {
195 diagnostics.push(Diagnostic::UnsupportedFeature {
196 feature: "channels besides R, G, B, A, and Y".into(),
197 path: format!("/channels/{}", channels[*first].name),
198 count: others.len(),
199 });
200 }
201 for channel in shown.iter().flatten().map(|index| &channels[*index]) {
202 check_channel(channel)?;
203 }
204 if shown
205 .iter()
206 .flatten()
207 .any(|index| channels[*index].sample_type == SampleType::F32)
208 {
209 diagnostics.push(Diagnostic::ReducedPrecision);
210 }
211
212 let matrix = to_bt709(color.chromaticities);
213 let (pixels, counts) = read_part(reader, part, &header, shown, matrix)?;
214 if counts.non_finite > 0 {
215 diagnostics.push(Diagnostic::NonFiniteSamples {
216 count: counts.non_finite,
217 });
218 }
219 if counts.out_of_range > 0 {
220 diagnostics.push(Diagnostic::OutOfHalfRange {
221 count: counts.out_of_range,
222 });
223 }
224 Ok(ExrImage {
225 width,
226 height,
227 pixels,
228 color,
229 diagnostics,
230 })
231}
232
233fn read_part(
234 reader: exr::block::reader::Reader<Cursor<&[u8]>>,
235 part: usize,
236 header: &exr::meta::header::Header,
237 shown: [Option<usize>; 4],
238 matrix: Option<[[f32; 3]; 3]>,
239) -> Result<(Arc<[u16]>, Counts), ExtensionError> {
240 let display = header.shared_attributes.display_window;
241 let mut pixels: Arc<[u16]> = std::iter::repeat_n(0, display.size.area() * 4).collect();
242 let mut canvas = Canvas::new(header, shown, matrix, Arc::make_mut(&mut pixels));
243 reader
244 .filter_chunks(false, |_, tile, block| {
245 block.layer == part && tile.is_largest_resolution_level()
246 })
247 .map_err(exr_error)?
248 .decompress_sequential(false, |_, block| {
249 canvas.place_block(&block, &header.channels);
250 Ok(())
251 })
252 .map_err(exr_error)?;
253 let Canvas { counts, .. } = canvas;
254 Ok((pixels, counts))
255}
256
257fn check_channel_lists(bytes: &[u8]) -> Result<(), ExtensionError> {
263 fn text(bytes: &[u8], at: &mut usize) -> Option<Vec<u8>> {
265 let rest = bytes.get(*at..)?;
266 let end = 1 + rest
267 .get(1..)?
268 .iter()
269 .take(256)
270 .position(|byte| *byte == 0)?;
271 *at += end + 1;
272 Some(rest[..end].to_vec())
273 }
274 let Some(flags) = bytes.get(4..8) else {
275 return Ok(());
276 };
277 let multipart = flags[1] & 0x10 != 0;
278 let mut at = 8;
279 loop {
280 let mut attributes = 0;
281 loop {
282 match bytes.get(at) {
283 None => return Ok(()),
284 Some(0) => {
285 at += 1;
286 break;
287 }
288 Some(_) => {}
289 }
290 let Some(name) = text(bytes, &mut at) else {
291 return Ok(());
292 };
293 attributes += 1;
294 let Some(kind) = text(bytes, &mut at) else {
295 return Ok(());
296 };
297 let Some(size) = bytes
298 .get(at..at + 4)
299 .and_then(|size| usize::try_from(i32::from_le_bytes(size.try_into().ok()?)).ok())
300 else {
301 return Ok(());
302 };
303 if kind == b"chlist" && name != b"channels" {
304 return Err(ExtensionError::Malformed(format!(
305 "a header holds a channel list besides `channels`: `{}`",
306 String::from_utf8_lossy(&name)
307 )));
308 }
309 at = at.saturating_add(4).saturating_add(size);
310 }
311 if !multipart || attributes == 0 {
313 return Ok(());
314 }
315 }
316}
317
318fn check_channel(channel: &ChannelDescription) -> Result<(), ExtensionError> {
320 if channel.sampling.x() != 1 || channel.sampling.y() != 1 {
321 return Err(ExtensionError::Unsupported(format!(
322 "channel {} is subsampled",
323 channel.name
324 )));
325 }
326 if channel.sample_type == SampleType::U32 {
327 return Err(ExtensionError::Unsupported(format!(
328 "channel {} holds integers, not colors",
329 channel.name
330 )));
331 }
332 Ok(())
333}
334
335fn check_part(
337 header: &exr::meta::header::Header,
338 width: u32,
339 height: u32,
340 part: usize,
341 parts: usize,
342) -> Result<Vec<Diagnostic>, ExtensionError> {
343 check_canvas(width, height)?;
344 let data_pixels = u64::try_from(header.layer_size.x())
345 .unwrap_or(u64::MAX)
346 .saturating_mul(u64::try_from(header.layer_size.y()).unwrap_or(u64::MAX));
347 if data_pixels > MAX_CANVAS_PIXELS {
348 return Err(ExtensionError::Budget(format!(
349 "a {}x{} data window is larger than {MAX_CANVAS_PIXELS} pixels",
350 header.layer_size.x(),
351 header.layer_size.y()
352 )));
353 }
354 let mut diagnostics = Vec::new();
355 if parts > 1 {
356 diagnostics.push(Diagnostic::UnsupportedFeature {
357 feature: "more than one part".into(),
358 path: format!("/parts/{}", usize::from(part == 0)),
359 count: parts - 1,
360 });
361 }
362 let aspect = header.shared_attributes.pixel_aspect;
363 if (aspect - 1.0).abs() > 1e-6 {
364 diagnostics.push(Diagnostic::UnsupportedFeature {
365 feature: format!("pixel aspect ratio {aspect}"),
366 path: "/pixelAspectRatio".into(),
367 count: 1,
368 });
369 }
370 Ok(diagnostics)
371}
372
373fn check_block_bytes(headers: &[exr::meta::header::Header]) -> Result<(), ExtensionError> {
377 let wide = |value: usize| u64::try_from(value).unwrap_or(u64::MAX);
378 for header in headers.iter().filter(|header| !header.deep) {
379 let (columns, rows) = match header.blocks {
380 BlockDescription::Tiles(tiles) => (tiles.tile_size.x(), tiles.tile_size.y()),
381 BlockDescription::ScanLines => (
382 header.layer_size.x(),
383 header.compression.scan_lines_per_block(),
384 ),
385 };
386 let bytes = wide(header.channels.bytes_per_pixel)
387 .saturating_mul(wide(columns))
388 .saturating_mul(wide(rows));
389 if bytes > MAX_EXR_BLOCK_BYTES {
390 return Err(ExtensionError::Budget(format!(
391 "a part decodes blocks of {bytes} bytes for its {} channels, more than {MAX_EXR_BLOCK_BYTES}",
392 header.channels.list.len()
393 )));
394 }
395 }
396 Ok(())
397}
398
399fn place(offset: i64, at: usize, size: usize) -> Option<usize> {
401 usize::try_from(offset + i64::try_from(at).ok()?)
402 .ok()
403 .filter(|position| *position < size)
404}
405
406struct Displayed {
407 samples_before: usize,
408 positions: std::ops::Range<usize>,
409}
410
411fn displayed(offset: i64, start: usize, count: usize, size: usize) -> Option<Displayed> {
412 let first = offset.checked_add(i64::try_from(start).ok()?)?;
413 let end = first.checked_add(i64::try_from(count).ok()?)?;
414 let samples_before = usize::try_from(first.checked_neg()?.max(0)).ok()?;
415 let positions = usize::try_from(first.max(0)).ok()?..usize::try_from(end).ok()?.min(size);
416 (positions.start < positions.end).then_some(Displayed {
417 samples_before,
418 positions,
419 })
420}
421
422struct Canvas<'a> {
424 width: usize,
425 height: usize,
426 offset: (i64, i64),
428 shown: [Option<usize>; 4],
430 rows: Rows,
431 pixels: &'a mut [u16],
432 counts: Counts,
433}
434
435enum Rows {
436 HalfBits,
437 Floats(FloatRows),
438}
439
440impl<'a> Canvas<'a> {
441 fn new(
442 header: &exr::meta::header::Header,
443 shown: [Option<usize>; 4],
444 matrix: Option<[[f32; 3]; 3]>,
445 pixels: &'a mut [u16],
446 ) -> Self {
447 let display = header.shared_attributes.display_window;
448 let position = header.own_attributes.layer_position;
449 let sample_types =
450 shown.map(|slot| slot.map(|index| header.channels.list[index].sample_type));
451 let shown_as_stored = matrix.is_none()
452 && sample_types
453 .iter()
454 .flatten()
455 .all(|sample_type| *sample_type == SampleType::F16);
456 let mut canvas = Self {
457 width: display.size.x(),
458 height: display.size.y(),
459 offset: (
460 i64::from(position.x()) - i64::from(display.position.x()),
461 i64::from(position.y()) - i64::from(display.position.y()),
462 ),
463 shown,
464 rows: if shown_as_stored {
465 Rows::HalfBits
466 } else {
467 Rows::Floats(FloatRows {
468 stored_as_half: sample_types
469 .map(|sample_type| sample_type == Some(SampleType::F16)),
470 matrix,
471 samples: Default::default(),
472 halves: Vec::new(),
473 row: Vec::new(),
474 })
475 },
476 pixels,
477 counts: Counts::default(),
478 };
479 canvas.fill_with_zero_samples(header.layer_size);
480 canvas
481 }
482
483 fn fill_with_zero_samples(&mut self, size: exr::math::Vec2<usize>) {
484 let alpha = if self.shown[3].is_some() { 0.0 } else { 1.0 };
485 let rgb = match &self.rows {
486 Rows::Floats(FloatRows {
487 matrix: Some(matrix),
488 ..
489 }) => multiply(matrix, [0.0; 3]),
490 _ => [0.0; 3],
491 };
492 let zero_samples =
493 [rgb[0], rgb[1], rgb[2], alpha].map(|value| f16::from_f32(value).to_bits());
494 if zero_samples == [0; 4] {
495 return;
496 }
497 let (Some(rows), Some(columns)) = (
498 displayed(self.offset.1, 0, size.y(), self.height),
499 displayed(self.offset.0, 0, size.x(), self.width),
500 ) else {
501 return;
502 };
503 let columns = columns.positions;
504 for y in rows.positions {
505 let row = &mut self.pixels[(y * self.width + columns.start) * 4..][..columns.len() * 4];
506 for pixel in row.as_chunks_mut::<4>().0 {
507 *pixel = zero_samples;
508 }
509 }
510 }
511
512 fn place_block(&mut self, block: &exr::block::UncompressedBlock, channels: &ChannelList) {
514 let last = channels.list.len() - 1;
515 let mut lines = [None::<&[u8]>; 4];
516 for line in block.lines(channels) {
517 let location = line.location;
518 for (slot, shown) in self.shown.iter().enumerate() {
519 if *shown == Some(location.channel) {
520 lines[slot] = Some(line.value);
521 }
522 }
523 if location.channel != last {
524 continue;
525 }
526 let row = std::mem::take(&mut lines);
527 let Some(y) = place(self.offset.1, location.position.y(), self.height) else {
528 continue;
529 };
530 let Some(Displayed {
531 samples_before,
532 positions,
533 }) = displayed(
534 self.offset.0,
535 location.position.x(),
536 location.sample_count,
537 self.width,
538 )
539 else {
540 continue;
541 };
542 let target =
543 &mut self.pixels[(y * self.width + positions.start) * 4..][..positions.len() * 4];
544 match &mut self.rows {
545 Rows::HalfBits => {
546 place_half_bits(&row, samples_before, target, &mut self.counts);
547 }
548 Rows::Floats(floats) => {
549 floats.place(&row, samples_before, target, &mut self.counts);
550 }
551 }
552 }
553 }
554}
555
556const HALF_NON_FINITE: u16 = f16::INFINITY.to_bits();
557const HALF_ONE: u16 = f16::ONE.to_bits();
558const HALF_NEGATIVE_ZERO: u16 = f16::NEG_ZERO.to_bits();
559
560fn place_half_bits(
561 lines: &[Option<&[u8]>; 4],
562 samples_before: usize,
563 target: &mut [u16],
564 counts: &mut Counts,
565) {
566 for (slot, line) in lines.iter().enumerate() {
567 let pixels = target.as_chunks_mut::<4>().0;
568 let Some(line) = line else {
569 let missing = if slot == 3 { HALF_ONE } else { 0 };
570 for pixel in pixels {
571 pixel[slot] = missing;
572 }
573 continue;
574 };
575 let samples = line
576 .as_chunks::<2>()
577 .0
578 .iter()
579 .skip(samples_before)
580 .map(|sample| u16::from_ne_bytes(*sample));
581 for (pixel, bits) in pixels.iter_mut().zip(samples) {
582 pixel[slot] = if bits & HALF_NON_FINITE == HALF_NON_FINITE {
583 counts.non_finite += 1;
584 0
585 } else if slot == 3 && bits > HALF_NEGATIVE_ZERO {
586 0
587 } else if slot == 3 && bits > HALF_ONE && bits < HALF_NEGATIVE_ZERO {
588 HALF_ONE
589 } else {
590 bits
591 };
592 }
593 }
594}
595
596struct FloatRows {
597 stored_as_half: [bool; 4],
598 matrix: Option<[[f32; 3]; 3]>,
599 samples: [Vec<f32>; 4],
600 halves: Vec<u16>,
601 row: Vec<f32>,
602}
603
604impl FloatRows {
605 fn place(
606 &mut self,
607 lines: &[Option<&[u8]>; 4],
608 samples_before: usize,
609 target: &mut [u16],
610 counts: &mut Counts,
611 ) {
612 let count = target.len() / 4;
613 for (slot, samples) in self.samples.iter_mut().enumerate() {
614 samples.clear();
615 if let Some(line) = lines[slot] {
616 if self.stored_as_half[slot] {
617 self.halves.clear();
618 self.halves.extend(
619 line.as_chunks::<2>()
620 .0
621 .iter()
622 .skip(samples_before)
623 .take(count)
624 .map(|sample| u16::from_ne_bytes(*sample)),
625 );
626 samples.resize(self.halves.len(), 0.0);
627 self.halves
628 .reinterpret_cast::<f16>()
629 .convert_to_f32_slice(samples);
630 } else {
631 samples.extend(
632 line.as_chunks::<4>()
633 .0
634 .iter()
635 .skip(samples_before)
636 .take(count)
637 .map(|sample| f32::from_ne_bytes(*sample)),
638 );
639 }
640 for sample in samples.iter_mut() {
641 if !sample.is_finite() {
642 counts.non_finite += 1;
643 *sample = 0.0;
644 }
645 }
646 }
647 samples.resize(count, if slot == 3 { 1.0 } else { 0.0 });
648 }
649 let [red, green, blue, alpha] = &self.samples;
650 self.row.clear();
651 self.row.resize(count * 4, 0.0);
652 let channels = red.iter().zip(green).zip(blue).zip(alpha);
653 for (pixel, (((red, green), blue), alpha)) in
654 self.row.as_chunks_mut::<4>().0.iter_mut().zip(channels)
655 {
656 let mut rgb = [*red, *green, *blue];
657 if let Some(matrix) = &self.matrix {
658 rgb = multiply(matrix, rgb);
659 }
660 *pixel = [rgb[0], rgb[1], rgb[2], alpha.clamp(0.0, 1.0)];
661 }
662 target
663 .reinterpret_cast_mut::<f16>()
664 .convert_from_f32_slice(&self.row);
665 for (bits, value) in target.iter_mut().zip(&self.row) {
666 if *bits & HALF_NON_FINITE != HALF_NON_FINITE {
667 continue;
668 }
669 *bits = if value.is_nan() {
670 counts.non_finite += 1;
671 0
672 } else {
673 counts.out_of_range += 1;
674 if *value > 0.0 { f16::MAX } else { f16::MIN }.to_bits()
675 };
676 }
677 }
678}
679
680#[derive(Default)]
682struct Counts {
683 non_finite: usize,
684 out_of_range: usize,
685}
686
687fn channels_shown(names: impl Iterator<Item = String>) -> Option<[Option<usize>; 4]> {
689 let names = names.collect::<Vec<_>>();
690 let find = |name: &str| names.iter().position(|candidate| candidate == name);
691 let alpha = find("A");
692 match (find("R"), find("G"), find("B"), find("Y")) {
693 (Some(red), Some(green), Some(blue), _) => {
694 Some([Some(red), Some(green), Some(blue), alpha])
695 }
696 (_, _, _, Some(luma)) => Some([Some(luma), Some(luma), Some(luma), alpha]),
697 _ => None,
698 }
699}
700
701fn exr_error(error: exr::error::Error) -> ExtensionError {
702 match error {
703 exr::error::Error::NotSupported(message) => ExtensionError::Unsupported(message.into()),
704 other => ExtensionError::Malformed(other.to_string()),
705 }
706}
707
708fn file_color(declared: Option<exr::meta::attribute::Chromaticities>) -> LinearColor {
710 let Some(declared) = declared else {
711 return LinearColor {
712 primaries: Some(LinearPrimaries::Bt709),
713 chromaticities: named_chromaticities(LinearPrimaries::Bt709),
714 origin: ColorOrigin::FormatDefault,
715 };
716 };
717 let chromaticities = [declared.red, declared.green, declared.blue, declared.white]
718 .map(|point| [point.x(), point.y()]);
719 LinearColor {
720 primaries: PRIMARIES.into_iter().find(|named| {
721 named_chromaticities(*named)
722 .iter()
723 .flatten()
724 .zip(chromaticities.iter().flatten())
725 .all(|(a, b)| (a - b).abs() < 5e-4)
726 }),
727 chromaticities,
728 origin: ColorOrigin::File,
729 }
730}
731
732const PRIMARIES: [LinearPrimaries; 5] = [
733 LinearPrimaries::Bt709,
734 LinearPrimaries::Bt2020,
735 LinearPrimaries::P3D65,
736 LinearPrimaries::AcesAp0,
737 LinearPrimaries::AcesAp1,
738];
739
740const D65: [f32; 2] = [0.3127, 0.3290];
741const ACES_WHITE: [f32; 2] = [0.32168, 0.33767];
742
743pub(crate) const fn named_chromaticities(primaries: LinearPrimaries) -> [[f32; 2]; 4] {
745 match primaries {
746 LinearPrimaries::Bt709 => [[0.64, 0.33], [0.30, 0.60], [0.15, 0.06], D65],
747 LinearPrimaries::Bt2020 => [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046], D65],
748 LinearPrimaries::P3D65 => [[0.680, 0.320], [0.265, 0.690], [0.150, 0.060], D65],
749 LinearPrimaries::AcesAp0 => [[0.7347, 0.2653], [0.0, 1.0], [0.0001, -0.0770], ACES_WHITE],
750 LinearPrimaries::AcesAp1 => [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], ACES_WHITE],
751 }
752}
753
754type Matrix = [[f64; 3]; 3];
755
756fn to_bt709(chromaticities: [[f32; 2]; 4]) -> Option<[[f32; 3]; 3]> {
758 let bt709 = named_chromaticities(LinearPrimaries::Bt709);
759 if chromaticities == bt709 {
760 return None;
761 }
762 let to_xyz = rgb_to_xyz(chromaticities);
763 let adapt = bradford(chromaticities[3], D65);
764 let from_xyz = invert(&rgb_to_xyz(bt709));
765 let matrix = product(&from_xyz, &product(&adapt, &to_xyz));
766 #[allow(clippy::cast_possible_truncation)]
768 Some(matrix.map(|row| row.map(|value| value as f32)))
769}
770
771fn defines_color_space(chromaticities: [[f32; 2]; 4]) -> bool {
773 to_bt709(chromaticities)
774 .is_none_or(|matrix| matrix.iter().flatten().all(|value| value.is_finite()))
775}
776
777fn multiply(matrix: &[[f32; 3]; 3], rgb: [f32; 3]) -> [f32; 3] {
778 matrix.map(|row| row[0] * rgb[0] + row[1] * rgb[1] + row[2] * rgb[2])
779}
780
781fn xyz_of(point: [f32; 2]) -> [f64; 3] {
782 let (x, y) = (f64::from(point[0]), f64::from(point[1]));
783 [x / y, 1.0, (1.0 - x - y) / y]
784}
785
786fn rgb_to_xyz(chromaticities: [[f32; 2]; 4]) -> Matrix {
788 let columns = [0, 1, 2].map(|index| xyz_of(chromaticities[index]));
789 let primaries = [0, 1, 2].map(|row| columns.map(|column| column[row]));
790 let white = xyz_of(chromaticities[3]);
791 let scale = apply(&invert(&primaries), white);
792 primaries.map(|row| [row[0] * scale[0], row[1] * scale[1], row[2] * scale[2]])
793}
794
795fn bradford(from: [f32; 2], to: [f32; 2]) -> Matrix {
797 const CONE: Matrix = [
798 [0.8951, 0.2664, -0.1614],
799 [-0.7502, 1.7135, 0.0367],
800 [0.0389, -0.0685, 1.0296],
801 ];
802 let source = apply(&CONE, xyz_of(from));
803 let target = apply(&CONE, xyz_of(to));
804 let scale = [0, 1, 2].map(|index| {
805 let mut row = [0.0; 3];
806 row[index] = target[index] / source[index];
807 row
808 });
809 product(&invert(&CONE), &product(&scale, &CONE))
810}
811
812fn apply(matrix: &Matrix, vector: [f64; 3]) -> [f64; 3] {
813 matrix.map(|row| row[0] * vector[0] + row[1] * vector[1] + row[2] * vector[2])
814}
815
816fn product(a: &Matrix, b: &Matrix) -> Matrix {
817 let mut out = [[0.0; 3]; 3];
818 for (row, out_row) in out.iter_mut().enumerate() {
819 for (column, value) in out_row.iter_mut().enumerate() {
820 *value = (0..3).map(|k| a[row][k] * b[k][column]).sum();
821 }
822 }
823 out
824}
825
826fn invert(m: &Matrix) -> Matrix {
827 let cofactor =
828 |r0: usize, r1: usize, c0: usize, c1: usize| m[r0][c0] * m[r1][c1] - m[r0][c1] * m[r1][c0];
829 let adjugate = [
830 [
831 cofactor(1, 2, 1, 2),
832 -cofactor(0, 2, 1, 2),
833 cofactor(0, 1, 1, 2),
834 ],
835 [
836 -cofactor(1, 2, 0, 2),
837 cofactor(0, 2, 0, 2),
838 -cofactor(0, 1, 0, 2),
839 ],
840 [
841 cofactor(1, 2, 0, 1),
842 -cofactor(0, 2, 0, 1),
843 cofactor(0, 1, 0, 1),
844 ],
845 ];
846 let determinant =
847 m[0][0] * adjugate[0][0] + m[0][1] * adjugate[1][0] + m[0][2] * adjugate[2][0];
848 adjugate.map(|row| row.map(|value| value / determinant))
849}
850
851#[cfg(test)]
852pub(crate) fn matrix_to_bt709(primaries: LinearPrimaries) -> Option<[[f32; 3]; 3]> {
853 to_bt709(named_chromaticities(primaries))
854}