Create new library Raw-rs including a basic TIFF decoder (#1757)

* add a basic tiff decoder in raw-rs

* cargo fmt

* add readme and license files

* add warning about being in-progress

* add testing framework for raw-rs

* add new type IFD and rename tag

* remove test_each and merge into single test

* cargo fmt

* make sure images folder stays in git

* rename image_length with image_height

* change name of test file

* Readme changes

---------

Co-authored-by: Keavon Chambers <keavon@keavon.com>
This commit is contained in:
Elbert Ronnie 2024-06-02 17:28:06 +05:30 committed by GitHub
parent 6d74abb4de
commit 72ccba09af
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 1354 additions and 0 deletions

42
Cargo.lock generated
View File

@ -1355,6 +1355,19 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
[[package]]
name = "downloader"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d05213e96f184578b5f70105d4d0a644a168e99e12d7bea0b200c15d67b5c182"
dependencies = [
"futures",
"rand 0.8.5",
"reqwest",
"thiserror",
"tokio",
]
[[package]]
name = "dtoa"
version = "1.0.9"
@ -3194,6 +3207,25 @@ version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ec2a862134d2a7d32d7983ddcdd1c4923530833c9f2ea1a44fc5fa473989058"
[[package]]
name = "libraw-rs"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24ec60aab878560c299c6e70a0c6dc2278a2159ac6fe09650917266b8985387f"
dependencies = [
"libraw-rs-sys",
]
[[package]]
name = "libraw-rs-sys"
version = "0.0.4+libraw-0.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba094a3b8b04cc42fdeafaff06f81d3b13a7d01cc7a8eae55b943dae1b65c3cc"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "libredox"
version = "0.0.2"
@ -4578,6 +4610,16 @@ version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8a99fddc9f0ba0a85884b8d14e3592853e787d581ca1816c91349b10e4eeab"
[[package]]
name = "raw-rs"
version = "0.0.1"
dependencies = [
"downloader",
"libraw-rs",
"num_enum 0.7.2",
"thiserror",
]
[[package]]
name = "raw-window-handle"
version = "0.5.2"

View File

@ -18,6 +18,7 @@ members = [
"node-graph/gpu-compiler/gpu-compiler-bin-wrapper",
"libraries/dyn-any",
"libraries/bezier-rs",
"libraries/raw-rs",
"website/other/bezier-rs-demos/wasm",
]
resolver = "2"

2
libraries/raw-rs/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
tests/images/*
!tests/images/.gitkeep

View File

@ -0,0 +1,21 @@
[package]
name = "raw-rs"
version = "0.0.1"
edition = "2021"
authors = ["Graphite Authors <contact@graphite.rs>"]
description = "A library to extract images from camera raw files"
license = "MIT OR Apache-2.0"
readme = "README.md"
keywords = ["raw", "tiff", "camera", "image"]
categories = ["multimedia::images", "multimedia::encoding"]
homepage = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/raw-rs"
repository = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/raw-rs"
documentation = "https://docs.rs/raw-rs"
[dependencies]
num_enum = "0.7.2"
thiserror = { workspace = true }
[dev-dependencies]
libraw-rs = "0.0.4"
downloader = "0.2.7"

View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,17 @@
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -0,0 +1,11 @@
[crates.io](https://crates.io/crates/raw-rs) • [docs.rs](https://docs.rs/raw-rs) • [repo](https://github.com/GraphiteEditor/Graphite/tree/master/libraries/raw-rs)
# Raw-rs
A library to extract images from camera raw files.
**WARNING**: This library is currently in-progress and not functional yet.
This library is built to extract the images from the raw files of Sony's cameras. In the future the library will add support for all other major camera manufacturers.
Raw-rs is built for the needs of [Graphite](https://graphite.rs), an open source 2D graphics editor. We hope it may be useful to others, but presently Graphite is its primary user. Pull requests are welcomed for new features, code cleanup, ergonomic enhancements, performance improvements, and documentation clarifications.

View File

@ -0,0 +1 @@
pub mod uncompressed;

View File

@ -0,0 +1,47 @@
use crate::tiff::file::TiffRead;
use crate::tiff::tags::{BITS_PER_SAMPLE, CFA_PATTERN, CFA_PATTERN_DIM, COMPRESSION, IMAGE_LENGTH, IMAGE_WIDTH, ROWS_PER_STRIP, SAMPLES_PER_PIXEL, STRIP_BYTE_COUNTS, STRIP_OFFSETS};
use crate::tiff::Ifd;
use crate::RawImage;
use std::io::{Read, Seek};
pub fn decode<R: Read + Seek>(ifd: Ifd, file: &mut TiffRead<R>) -> RawImage {
let strip_offsets = ifd.get(STRIP_OFFSETS, file).unwrap();
let strip_byte_counts = ifd.get(STRIP_BYTE_COUNTS, file).unwrap();
assert!(strip_offsets.len() == strip_byte_counts.len());
let image_width: usize = ifd.get(IMAGE_WIDTH, file).unwrap().try_into().unwrap();
let image_height: usize = ifd.get(IMAGE_LENGTH, file).unwrap().try_into().unwrap();
let rows_per_strip: usize = ifd.get(ROWS_PER_STRIP, file).unwrap().try_into().unwrap();
let bits_per_sample: usize = ifd.get(BITS_PER_SAMPLE, file).unwrap().into();
let bytes_per_sample: usize = bits_per_sample.div_ceil(8);
let samples_per_pixel: usize = ifd.get(SAMPLES_PER_PIXEL, file).unwrap().into();
let compression = ifd.get(COMPRESSION, file).unwrap();
assert!(compression == 1); // 1 is the value for uncompressed format
// let photometric_interpretation = ifd.get(PHOTOMETRIC_INTERPRETATION, file).unwrap();
let [cfa_pattern_width, cfa_pattern_height] = ifd.get(CFA_PATTERN_DIM, file).unwrap();
assert!(cfa_pattern_width == 2 && cfa_pattern_height == 2);
let cfa_pattern = ifd.get(CFA_PATTERN, file).unwrap();
let rows_per_strip_last = image_height % rows_per_strip;
let bytes_per_row = bytes_per_sample * samples_per_pixel * image_width;
let mut image: Vec<u16> = Vec::with_capacity(image_height * image_width);
for i in 0..strip_offsets.len() {
file.seek_from_start(strip_offsets[i]).unwrap();
let row_count = if i == strip_offsets.len() { rows_per_strip_last } else { rows_per_strip };
for _ in 0..row_count {
for _ in 0..image_width {
image.push(file.read_u16().unwrap());
}
}
}
RawImage {
data: image,
width: image_width,
height: image_height,
}
}

View File

@ -0,0 +1,49 @@
pub mod decoder;
pub mod tiff;
use std::io::{Read, Seek};
use thiserror::Error;
use tiff::file::TiffRead;
use tiff::tags::{COMPRESSION, SUBIFD};
use tiff::{Ifd, TiffError};
pub struct RawImage {
pub data: Vec<u16>,
pub width: usize,
pub height: usize,
}
pub struct Image<T> {
pub data: Vec<T>,
pub width: usize,
pub height: usize,
pub channels: u8,
}
pub fn decode<R: Read + Seek>(reader: &mut R) -> Result<RawImage, DecoderError> {
let mut file = TiffRead::new(reader)?;
let ifd = Ifd::new_first_ifd(&mut file)?;
// TODO: This is only for the tests to pass for now. Replace this with the correct implementation when the decoder is complete.
let subifd = ifd.get(SUBIFD, &mut file)?;
Ok(decoder::uncompressed::decode(subifd, &mut file))
}
pub fn process_8bit(image: RawImage) -> Image<u8> {
todo!()
}
pub fn process_16bit(image: RawImage) -> Image<u16> {
todo!()
}
#[derive(Error, Debug)]
pub enum DecoderError {
#[error("An error occurred when trying to parse the TIFF format")]
TiffError(#[from] TiffError),
#[error("An error occurred when converting integer from one type to another")]
ConversionError(#[from] std::num::TryFromIntError),
#[error("An IO Error ocurred")]
IoError(#[from] std::io::Error),
}

View File

@ -0,0 +1,148 @@
use std::io::{Error, ErrorKind, Read, Result, Seek, SeekFrom};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Endian {
Little,
Big,
}
pub struct TiffRead<R: Read + Seek> {
reader: R,
endian: Endian,
}
impl<R: Read + Seek> TiffRead<R> {
pub fn new(mut reader: R) -> Result<Self> {
let error = Error::new(ErrorKind::InvalidData, "Invalid Tiff format");
let mut data = [0u8; 2];
reader.read_exact(&mut data)?;
let endian = if data[0] == 0x49 && data[1] == 0x49 {
Endian::Little
} else if data[0] == 0x4d && data[1] == 0x4d {
Endian::Big
} else {
return Err(error);
};
reader.read_exact(&mut data)?;
let magic_number = match endian {
Endian::Little => u16::from_le_bytes(data),
Endian::Big => u16::from_be_bytes(data),
};
if magic_number != 42 {
return Err(error);
}
Ok(Self { reader, endian })
}
}
impl<R: Read + Seek> Read for TiffRead<R> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
self.reader.read(buf)
}
}
impl<R: Read + Seek> Seek for TiffRead<R> {
fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
self.reader.seek(pos)
}
}
impl<R: Read + Seek> TiffRead<R> {
pub fn seek_from_start(&mut self, offset: u32) -> Result<u64> {
self.reader.seek(SeekFrom::Start(offset.into()))
}
pub fn read_ascii(&mut self) -> Result<char> {
let data = self.read_n::<1>()?;
Ok(data[0] as char)
}
pub fn read_n<const N: usize>(&mut self) -> Result<[u8; N]> {
let mut data = [0u8; N];
self.read_exact(&mut data)?;
Ok(data)
}
pub fn read_u8(&mut self) -> Result<u8> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u8::from_le_bytes(data)),
Endian::Big => Ok(u8::from_be_bytes(data)),
}
}
pub fn read_u16(&mut self) -> Result<u16> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u16::from_le_bytes(data)),
Endian::Big => Ok(u16::from_be_bytes(data)),
}
}
pub fn read_u32(&mut self) -> Result<u32> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u32::from_le_bytes(data)),
Endian::Big => Ok(u32::from_be_bytes(data)),
}
}
pub fn read_u64(&mut self) -> Result<u64> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(u64::from_le_bytes(data)),
Endian::Big => Ok(u64::from_be_bytes(data)),
}
}
pub fn read_i8(&mut self) -> Result<i8> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i8::from_le_bytes(data)),
Endian::Big => Ok(i8::from_be_bytes(data)),
}
}
pub fn read_i16(&mut self) -> Result<i16> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i16::from_le_bytes(data)),
Endian::Big => Ok(i16::from_be_bytes(data)),
}
}
pub fn read_i32(&mut self) -> Result<i32> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i32::from_le_bytes(data)),
Endian::Big => Ok(i32::from_be_bytes(data)),
}
}
pub fn read_i64(&mut self) -> Result<i64> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(i64::from_le_bytes(data)),
Endian::Big => Ok(i64::from_be_bytes(data)),
}
}
pub fn read_f32(&mut self) -> Result<f32> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(f32::from_le_bytes(data)),
Endian::Big => Ok(f32::from_be_bytes(data)),
}
}
pub fn read_f64(&mut self) -> Result<f64> {
let data = self.read_n()?;
match self.endian {
Endian::Little => Ok(f64::from_le_bytes(data)),
Endian::Big => Ok(f64::from_be_bytes(data)),
}
}
}

View File

@ -0,0 +1,138 @@
pub mod file;
pub mod tags;
mod types;
pub mod values;
use file::TiffRead;
use num_enum::{FromPrimitive, IntoPrimitive, TryFromPrimitive};
use std::io::{Read, Seek};
use thiserror::Error;
use tags::Tag;
use types::TagType;
#[derive(Copy, Clone, Debug, PartialEq, Eq, FromPrimitive, IntoPrimitive)]
#[repr(u16)]
pub enum TagId {
ImageWidth = 0x100,
ImageLength = 0x101,
BitsPerSample = 0x102,
Compression = 0x103,
PhotometricInterpretation = 0x104,
StripOffsets = 0x111,
SamplesPerPixel = 0x115,
RowsPerStrip = 0x116,
StripByteCounts = 0x117,
SubIfd = 0x14a,
JpegOffset = 0x201,
JpegLength = 0x202,
CfaPatternDim = 0x828d,
CfaPattern = 0x828e,
#[num_enum(catch_all)]
Unknown(u16),
}
#[repr(u16)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, TryFromPrimitive, IntoPrimitive)]
pub enum IfdTagType {
Ascii = 2,
Byte = 1,
Short = 3,
Long = 4,
Rational = 5,
SByte = 6,
SShort = 8,
SLong = 9,
SRational = 10,
Float = 11,
Double = 12,
Undefined = 7,
}
#[derive(Copy, Clone, Debug)]
pub struct IfdEntry {
tag: TagId,
type_: u16,
count: u32,
value: u32,
}
#[derive(Clone, Debug)]
pub struct Ifd {
current_ifd_offset: u32,
ifd_entries: Vec<IfdEntry>,
next_ifd_offset: Option<u32>,
}
impl Ifd {
pub fn new_first_ifd<R: Read + Seek>(file: &mut TiffRead<R>) -> std::io::Result<Self> {
file.seek_from_start(4)?;
let current_ifd_offset = file.read_u32()?;
Ifd::new_from_offset(file, current_ifd_offset)
}
pub fn new_from_offset<R: Read + Seek>(file: &mut TiffRead<R>, offset: u32) -> std::io::Result<Self> {
if offset == 0 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "Ifd at offset zero does not exist"));
}
file.seek_from_start(offset)?;
let num = file.read_u16()?;
let mut ifd_entries = Vec::with_capacity(num.into());
for _ in 0..num {
let tag = file.read_u16()?.into();
let type_ = file.read_u16()?;
let count = file.read_u32()?;
let value = file.read_u32()?;
ifd_entries.push(IfdEntry { tag, type_, count, value });
}
let next_ifd_offset = file.read_u32()?;
let next_ifd_offset = if next_ifd_offset == 0 { Some(next_ifd_offset) } else { None };
Ok(Ifd {
current_ifd_offset: offset,
ifd_entries,
next_ifd_offset,
})
}
fn next_ifd<R: Read + Seek>(&self, file: &mut TiffRead<R>) -> std::io::Result<Self> {
Ifd::new_from_offset(file, self.next_ifd_offset.unwrap_or(0))
}
pub fn ifd_entries(&self) -> &[IfdEntry] {
&self.ifd_entries
}
pub fn iter(&self) -> impl Iterator<Item = &IfdEntry> {
self.ifd_entries.iter()
}
pub fn get<T: TagType, R: Read + Seek>(&self, tag: Tag<T>, file: &mut TiffRead<R>) -> Result<T::Output, TiffError> {
let tag_id = tag.id();
let index: u32 = self.iter().position(|x| x.tag == tag_id).ok_or(TiffError::InvalidTag)?.try_into()?;
file.seek_from_start(self.current_ifd_offset + 2 + 12 * index + 2)?;
T::read(file)
}
}
#[derive(Error, Debug)]
pub enum TiffError {
#[error("The value was invalid")]
InvalidValue,
#[error("The type was invalid")]
InvalidType,
#[error("The count was invalid")]
InvalidCount,
#[error("The tag was invalid")]
InvalidTag,
#[error("An error occurred when converting integer from one type to another")]
ConversionError(#[from] std::num::TryFromIntError),
#[error("An IO Error ocurred")]
IoError(#[from] std::io::Error),
}

View File

@ -0,0 +1,41 @@
use super::types::{Array, ConstArray, TagType, TypeByte, TypeIfd, TypeLong, TypeNumber, TypeShort};
use super::TagId;
pub struct Tag<T: TagType> {
tag_id: TagId,
name: &'static str,
tag_type: std::marker::PhantomData<T>,
}
impl<T: TagType> Tag<T> {
const fn new(tag_id: TagId, name: &'static str) -> Self {
Tag {
tag_id,
name,
tag_type: std::marker::PhantomData,
}
}
pub fn id(&self) -> TagId {
self.tag_id
}
pub fn name(&self) -> &'static str {
self.name
}
}
pub const IMAGE_WIDTH: Tag<TypeNumber> = Tag::new(TagId::ImageWidth, "Image Width");
pub const IMAGE_LENGTH: Tag<TypeNumber> = Tag::new(TagId::ImageLength, "Image Length");
pub const BITS_PER_SAMPLE: Tag<TypeShort> = Tag::new(TagId::BitsPerSample, "Bits per Sample");
pub const COMPRESSION: Tag<TypeShort> = Tag::new(TagId::Compression, "Compression");
pub const PHOTOMETRIC_INTERPRETATION: Tag<TypeShort> = Tag::new(TagId::PhotometricInterpretation, "Photometric Interpretation");
pub const STRIP_OFFSETS: Tag<Array<TypeNumber>> = Tag::new(TagId::StripOffsets, "Strip Offsets");
pub const SAMPLES_PER_PIXEL: Tag<TypeShort> = Tag::new(TagId::SamplesPerPixel, "Samples per Pixel");
pub const ROWS_PER_STRIP: Tag<TypeNumber> = Tag::new(TagId::RowsPerStrip, "Rows per Strip");
pub const STRIP_BYTE_COUNTS: Tag<Array<TypeNumber>> = Tag::new(TagId::StripByteCounts, "Strip Byte Counts");
pub const SUBIFD: Tag<TypeIfd> = Tag::new(TagId::SubIfd, "SubIFD");
pub const JPEG_OFFSET: Tag<TypeLong> = Tag::new(TagId::JpegOffset, "Jpeg Offset");
pub const JPEG_LENGTH: Tag<TypeLong> = Tag::new(TagId::JpegLength, "Jpeg Length");
pub const CFA_PATTERN_DIM: Tag<ConstArray<TypeShort, 2>> = Tag::new(TagId::CfaPatternDim, "CFA Pattern Dimension");
pub const CFA_PATTERN: Tag<Array<TypeByte>> = Tag::new(TagId::CfaPattern, "CFA Pattern");

View File

@ -0,0 +1,359 @@
use std::io::{Read, Seek};
use super::file::TiffRead;
use super::values::Rational;
use super::{Ifd, IfdTagType, TiffError};
pub struct TypeAscii;
pub struct TypeByte;
pub struct TypeShort;
pub struct TypeLong;
pub struct TypeRational;
pub struct TypeSByte;
pub struct TypeSShort;
pub struct TypeSLong;
pub struct TypeSRational;
pub struct TypeFloat;
pub struct TypeDouble;
pub struct TypeUndefined;
pub struct TypeNumber;
pub struct TypeSNumber;
pub struct TypeIfd;
pub trait PrimitiveType {
type Output;
fn get_size(type_: IfdTagType) -> Option<u32>;
fn read_primitive<R: Read + Seek>(type_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError>;
}
impl PrimitiveType for TypeAscii {
type Output = char;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Ascii => Some(1),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let value = file.read_ascii()?;
if value.is_ascii() {
Ok(value)
} else {
Err(TiffError::InvalidValue)
}
}
}
impl PrimitiveType for TypeByte {
type Output = u8;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Byte => Some(1),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_u8()?)
}
}
impl PrimitiveType for TypeShort {
type Output = u16;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Short => Some(2),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_u16()?)
}
}
impl PrimitiveType for TypeLong {
type Output = u32;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Long => Some(4),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_u32()?)
}
}
impl PrimitiveType for TypeRational {
type Output = Rational<u32>;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Rational => Some(8),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(type_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let numerator = TypeLong::read_primitive(type_, file)?;
let denominator = TypeLong::read_primitive(type_, file)?;
Ok(Rational { numerator, denominator })
}
}
impl PrimitiveType for TypeSByte {
type Output = i8;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::SByte => Some(1),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_i8()?)
}
}
impl PrimitiveType for TypeSShort {
type Output = i16;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::SShort => Some(2),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_i16()?)
}
}
impl PrimitiveType for TypeSLong {
type Output = i32;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::SLong => Some(4),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_i32()?)
}
}
impl PrimitiveType for TypeSRational {
type Output = Rational<i32>;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::SRational => Some(8),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(type_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let numerator = TypeSLong::read_primitive(type_, file)?;
let denominator = TypeSLong::read_primitive(type_, file)?;
Ok(Rational { numerator, denominator })
}
}
impl PrimitiveType for TypeFloat {
type Output = f32;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Float => Some(4),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_f32()?)
}
}
impl PrimitiveType for TypeDouble {
type Output = f64;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Double => Some(8),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(file.read_f64()?)
}
}
impl PrimitiveType for TypeUndefined {
type Output = ();
fn get_size(_: IfdTagType) -> Option<u32> {
todo!()
}
fn read_primitive<R: Read + Seek>(_: IfdTagType, _: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
todo!()
}
}
impl PrimitiveType for TypeNumber {
type Output = u32;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Byte => TypeByte::get_size(type_),
IfdTagType::Short => TypeShort::get_size(type_),
IfdTagType::Long => TypeLong::get_size(type_),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(type_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(match type_ {
IfdTagType::Byte => TypeByte::read_primitive(type_, file)?.into(),
IfdTagType::Short => TypeShort::read_primitive(type_, file)?.into(),
IfdTagType::Long => TypeLong::read_primitive(type_, file)?,
_ => unreachable!(),
})
}
}
impl PrimitiveType for TypeSNumber {
type Output = i32;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::SByte => TypeSByte::get_size(type_),
IfdTagType::SShort => TypeSShort::get_size(type_),
IfdTagType::SLong => TypeSLong::get_size(type_),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(type_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
Ok(match type_ {
IfdTagType::SByte => TypeSByte::read_primitive(type_, file)?.into(),
IfdTagType::SShort => TypeSShort::read_primitive(type_, file)?.into(),
IfdTagType::SLong => TypeSLong::read_primitive(type_, file)?,
_ => unreachable!(),
})
}
}
impl PrimitiveType for TypeIfd {
type Output = Ifd;
fn get_size(type_: IfdTagType) -> Option<u32> {
match type_ {
IfdTagType::Long => Some(4),
_ => None,
}
}
fn read_primitive<R: Read + Seek>(type_: IfdTagType, file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let offset = TypeLong::read_primitive(type_, file)?;
Ok(Ifd::new_from_offset(file, offset)?)
}
}
pub trait TagType {
type Output;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError>;
}
impl<T: PrimitiveType> TagType for T {
type Output = T::Output;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let type_ = IfdTagType::try_from(file.read_u16()?).map_err(|_| TiffError::InvalidType)?;
let count = file.read_u32()?;
if count != 1 {
return Err(TiffError::InvalidCount);
}
let size = T::get_size(type_).ok_or(TiffError::InvalidType)?;
if count * size > 4 {
let offset = file.read_u32()?;
file.seek_from_start(offset)?;
}
T::read_primitive(type_, file)
}
}
pub struct Array<T: PrimitiveType> {
primitive_type: std::marker::PhantomData<T>,
}
pub struct ConstArray<T: PrimitiveType, const N: usize> {
primitive_type: std::marker::PhantomData<T>,
}
impl<T: PrimitiveType> TagType for Array<T> {
type Output = Vec<T::Output>;
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let type_ = IfdTagType::try_from(file.read_u16()?).map_err(|_| TiffError::InvalidType)?;
let count = file.read_u32()?;
let size = T::get_size(type_).ok_or(TiffError::InvalidType)?;
if count * size > 4 {
let offset = file.read_u32()?;
file.seek_from_start(offset)?;
}
let mut ans = Vec::with_capacity(count.try_into()?);
for _ in 0..count {
ans.push(T::read_primitive(type_, file)?);
}
Ok(ans)
}
}
impl<T: PrimitiveType, const N: usize> TagType for ConstArray<T, N> {
type Output = [T::Output; N];
fn read<R: Read + Seek>(file: &mut TiffRead<R>) -> Result<Self::Output, TiffError> {
let type_ = IfdTagType::try_from(file.read_u16()?).map_err(|_| TiffError::InvalidType)?;
let count = file.read_u32()?;
if count != N.try_into()? {
return Err(TiffError::InvalidCount);
}
let size = T::get_size(type_).ok_or(TiffError::InvalidType)?;
if count * size > 4 {
let offset = file.read_u32()?;
file.seek_from_start(offset)?;
}
let mut ans = Vec::with_capacity(count.try_into()?);
for _ in 0..count {
ans.push(T::read_primitive(type_, file)?);
}
ans.try_into().map_err(|_| TiffError::InvalidCount)
}
}

View File

@ -0,0 +1,4 @@
pub struct Rational<T> {
pub numerator: T,
pub denominator: T,
}

View File

@ -0,0 +1 @@

View File

@ -0,0 +1,271 @@
use std::collections::HashMap;
use std::fmt::Write;
use std::fs::{read_dir, File};
use std::io::{Cursor, Read};
use std::path::Path;
use raw_rs::RawImage;
use downloader::{Download, Downloader};
use libraw::Processor;
const TEST_FILES: [&str; 1] = ["ILCE-7M3-ARW2.3.5-blossoms.arw"];
const BASE_URL: &str = "https://static.graphite.rs/test-data/libraries/raw-rs/";
const BASE_PATH: &str = "./tests/images";
#[test]
fn test_images_matches_with_libraw() {
download_images();
let mut failed_tests = 0;
read_dir(BASE_PATH)
.unwrap()
.map(|dir_entry| dir_entry.unwrap().path())
.filter(|path| path.is_file() && path.file_name().map(|file_name| file_name != ".gitkeep").unwrap_or(false))
.for_each(|path| {
let mut f = File::open(&path).unwrap();
let mut content = vec![];
f.read_to_end(&mut content).unwrap();
print!("{} => ", path.display());
let raw_image = match test_raw_data(&content) {
Err(err_msg) => {
failed_tests += 1;
return println!("{}", err_msg);
}
Ok(raw_image) => raw_image,
};
// TODO: The code below is kept commented because raw data to final image processing is
// incomplete. Remove this once it is done.
// if let Err(err_msg) = test_final_image(&content, raw_image) {
// failed_tests += 1;
// return println!("{}", err_msg);
// };
println!("Passed");
});
if failed_tests != 0 {
panic!("{} images have failed the tests", failed_tests);
}
}
fn download_images() {
let mut path = Path::new(BASE_PATH).to_owned();
let mut downloads: Vec<Download> = Vec::new();
for filename in TEST_FILES {
path.push(filename);
if !path.exists() {
let url = BASE_URL.to_owned() + filename;
downloads.push(Download::new(&url).file_name(Path::new(filename)));
}
path.pop();
}
let mut downloader = Downloader::builder().download_folder(Path::new(BASE_PATH)).build().unwrap();
for download_summary in downloader.download(&downloads).unwrap() {
download_summary.unwrap();
}
}
fn test_raw_data(content: &[u8]) -> Result<RawImage, String> {
let processor = Processor::new();
let libraw_raw_image = processor.decode(content).unwrap();
let mut content = Cursor::new(content);
let raw_image = raw_rs::decode(&mut content).unwrap();
if libraw_raw_image.sizes().raw_height as usize != raw_image.height {
return Err(format!(
"The height of raw image is {} but the expected value was {}",
raw_image.height,
libraw_raw_image.sizes().raw_height
));
}
if libraw_raw_image.sizes().raw_width as usize != raw_image.width {
return Err(format!(
"The width of raw image is {} but the expected value was {}",
raw_image.width,
libraw_raw_image.sizes().raw_width
));
}
if (*libraw_raw_image).len() != raw_image.data.len() {
return Err(format!(
"The size of data of raw image is {} but the expected value was {}",
raw_image.data.len(),
(*libraw_raw_image).len()
));
}
if (*libraw_raw_image) != raw_image.data {
let mut err_msg = String::new();
write!(&mut err_msg, "The raw data does not match").unwrap();
if std::env::var("RAW_RS_TEST_PRINT_HISTOGRAM").is_ok() {
writeln!(err_msg).unwrap();
let mut histogram: HashMap<i32, usize> = HashMap::new();
let mut non_zero_count: usize = 0;
(*libraw_raw_image)
.iter()
.zip(raw_image.data.iter())
.map(|(&a, &b)| {
let a: i32 = a.into();
let b: i32 = b.into();
a - b
})
.filter(|&x| x != 0)
.for_each(|x| {
*histogram.entry(x).or_default() += 1;
non_zero_count += 1;
});
let total_pixels = raw_image.height * raw_image.width;
writeln!(err_msg, "{} ({:.5}%) pixels are different from expected", non_zero_count, non_zero_count as f64 / total_pixels as f64).unwrap();
writeln!(err_msg, "Diff Histogram:").unwrap();
let mut items: Vec<_> = histogram.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
}
return Err(err_msg);
}
Ok(raw_image)
}
fn test_final_image(content: &[u8], raw_image: RawImage) -> Result<(), String> {
let processor = Processor::new();
let libraw_image = processor.process_8bit(content).unwrap();
let image = raw_rs::process_8bit(raw_image);
if libraw_image.height() as usize != image.height {
return Err(format!("The height of image is {} but the expected value was {}", image.height, libraw_image.height()));
}
if libraw_image.width() as usize != image.width {
return Err(format!("The width of image is {} but the expected value was {}", image.width, libraw_image.width()));
}
if (*libraw_image).len() != image.data.len() {
return Err(format!("The size of data of image is {} but the expected value was {}", image.data.len(), (*libraw_image).len()));
}
if (*libraw_image) != image.data {
let mut err_msg = String::new();
write!(&mut err_msg, "The final image does not match").unwrap();
if std::env::var("RAW_RS_TEST_PRINT_HISTOGRAM").is_ok() {
writeln!(err_msg).unwrap();
let mut histogram_red: HashMap<i16, usize> = HashMap::new();
let mut histogram_green: HashMap<i16, usize> = HashMap::new();
let mut histogram_blue: HashMap<i16, usize> = HashMap::new();
let mut non_zero_count: usize = 0;
let mut non_zero_count_red: usize = 0;
let mut non_zero_count_green: usize = 0;
let mut non_zero_count_blue: usize = 0;
(*libraw_image)
.chunks_exact(3)
.zip(image.data.chunks_exact(3))
.map(|(a, b)| {
let a: [u8; 3] = a.try_into().unwrap();
let b: [u8; 3] = b.try_into().unwrap();
(a, b)
})
.map(|([r1, g1, b1], [r2, g2, b2])| {
let r1: i16 = r1.into();
let g1: i16 = g1.into();
let b1: i16 = b1.into();
let r2: i16 = r2.into();
let g2: i16 = g2.into();
let b2: i16 = b2.into();
[r1 - r2, g1 - g2, b1 - b2]
})
.filter(|&[r, g, b]| r != 0 || g != 0 || b != 0)
.for_each(|[r, g, b]| {
non_zero_count += 1;
if r != 0 {
*histogram_red.entry(r).or_default() += 1;
non_zero_count_red += 1;
}
if g != 0 {
*histogram_green.entry(g).or_default() += 1;
non_zero_count_green += 1;
}
if b != 0 {
*histogram_blue.entry(b).or_default() += 1;
non_zero_count_blue += 1;
}
});
let total_pixels = image.height * image.width;
writeln!(err_msg, "{} ({:.5}%) pixels are different from expected", non_zero_count, non_zero_count as f64 / total_pixels as f64,).unwrap();
writeln!(
err_msg,
"{} ({:.5}%) red pixels are different from expected",
non_zero_count_red,
non_zero_count_red as f64 / total_pixels as f64,
)
.unwrap();
writeln!(
err_msg,
"{} ({:.5}%) green pixels are different from expected",
non_zero_count_green,
non_zero_count_green as f64 / total_pixels as f64,
)
.unwrap();
writeln!(
err_msg,
"{} ({:.5}%) blue pixels are different from expected",
non_zero_count_blue,
non_zero_count_blue as f64 / total_pixels as f64,
)
.unwrap();
writeln!(err_msg, "Diff Histogram for Red pixels:").unwrap();
let mut items: Vec<_> = histogram_red.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
writeln!(err_msg, "Diff Histogram for Green pixels:").unwrap();
let mut items: Vec<_> = histogram_green.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
writeln!(err_msg, "Diff Histogram for Blue pixels:").unwrap();
let mut items: Vec<_> = histogram_blue.iter().map(|(&a, &b)| (a, b)).collect();
items.sort();
for (key, value) in items {
writeln!(err_msg, "{:05}: {:05} ({:02.5}%)", key, value, value as f64 / total_pixels as f64).unwrap();
}
}
return Err(err_msg);
}
Ok(())
}