Rename Raw-rs to Rawkit (#2088)

* Rename within files

* Rename in CI

* Rename the folder and file names

* Rename raw_rs to rawkit

* Add example to README

* Add initial documentation

* Small API changes and extra documentation

* Bump versions and stuff

* Readme improvements

* Merge proc-macro crates into one

* Add README to rawkit-proc-macros

* Remove keywords and categories

* Add licenses to rawkit-proc-macros

---------

Co-authored-by: Keavon Chambers <keavon@keavon.com>
This commit is contained in:
Elbert Ronnie 2024-11-03 13:40:39 +05:30 committed by GitHub
parent 8d3da83606
commit 8fdecaa487
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
89 changed files with 664 additions and 356 deletions

View file

@ -113,19 +113,19 @@ jobs:
with:
command: check advisories
- name: 🔒 Check crate security advisories for /libraries/raw-rs
- name: 🔒 Check crate security advisories for /libraries/rawkit
uses: EmbarkStudios/cargo-deny-action@v1
with:
command: check advisories
manifest-path: libraries/raw-rs/Cargo.toml
manifest-path: libraries/rawkit/Cargo.toml
- name: 📜 Check crate license compatibility for root workspace
uses: EmbarkStudios/cargo-deny-action@v1
with:
command: check bans licenses sources
- name: 📜 Check crate license compatibility for /libraries/raw-rs
- name: 📜 Check crate license compatibility for /libraries/rawkit
uses: EmbarkStudios/cargo-deny-action@v1
with:
command: check bans licenses sources
manifest-path: libraries/raw-rs/Cargo.toml
manifest-path: libraries/rawkit/Cargo.toml

View file

@ -35,8 +35,8 @@ jobs:
# Run Clippy and filter output for the root workspace
CLIPPY_OUTPUT=$(cargo clippy --all-targets --all-features -- -W clippy::all 2>&1 | grep -vE "^(\s*Updating|\s*Download|\s*Compiling|\s*Checking|Finished)")
# Run Clippy and filter output for /libraries/raw-rs
cd libraries/raw-rs
# Run Clippy and filter output for /libraries/rawkit
cd libraries/rawkit
CLIPPY_OUTPUT+=$'\n\n'
CLIPPY_OUTPUT+=$(cargo clippy --all-targets --all-features -- -W clippy::all 2>&1 | grep -vE "^(\s*Updating|\s*Download|\s*Compiling|\s*Checking|Finished)")
cd ../..

View file

@ -1,16 +1,16 @@
name: "Library: Raw-rs"
name: "Library: Rawkit"
on:
push:
branches:
- master
paths:
- "libraries/raw-rs/**"
- "libraries/rawkit/**"
pull_request:
branches:
- master
paths:
- "libraries/raw-rs/**"
- "libraries/rawkit/**"
env:
CARGO_TERM_COLOR: always
@ -43,17 +43,17 @@ jobs:
- name: 🔬 Check Rust formatting
run: |
cd libraries/raw-rs
cd libraries/rawkit
cargo fmt --all -- --check
- name: 🦀 Build Rust code
run: |
cd libraries/raw-rs
cd libraries/rawkit
cargo build --release --all-features
- name: 🧪 Run Rust tests
run: |
cd libraries/raw-rs
cd libraries/rawkit
cargo test --release --all-features
- name: 📈 Run sccache stat for check

View file

@ -66,7 +66,7 @@ in
libsoup
webkitgtk
# For Raw-rs tests
# For Rawkit tests
libraw
# Use Mold as a linker

View file

@ -1,11 +0,0 @@
[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

@ -1,21 +0,0 @@
[package]
name = "build-camera-data"
version = "0.0.1"
publish = false
edition = "2021"
authors = ["Graphite Authors <contact@graphite.rs>"]
description = "Procedural macro to build the camera data into rust code"
license = "MIT OR Apache-2.0"
repository = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/raw-rs/build-camera-data"
[lib]
proc-macro = true
[dependencies]
# Workspace dependencies
quote = { workspace = true }
syn = { workspace = true }
# Required dependencies
toml = "0.8.15"
proc-macro2 = "1.0.88"

View file

@ -1,201 +0,0 @@
pub mod decoder;
pub mod demosaicing;
pub mod metadata;
pub mod postprocessing;
pub mod preprocessing;
pub mod processing;
pub mod tiff;
use crate::metadata::identify::CameraModel;
use processing::{Pixel, PixelTransform, RawPixel, RawPixelTransform};
use tag_derive::Tag;
use tiff::file::TiffRead;
use tiff::tags::{Compression, ImageLength, ImageWidth, Orientation, StripByteCounts, SubIfd, Tag};
use tiff::values::Transform;
use tiff::{Ifd, TiffError};
use std::io::{Read, Seek};
use thiserror::Error;
pub const CHANNELS_IN_RGB: usize = 3;
pub type Histogram = [[usize; 0x2000]; CHANNELS_IN_RGB];
pub enum SubtractBlack {
None,
Value(u16),
CfaGrid([u16; 4]),
}
pub struct RawImage {
pub data: Vec<u16>,
pub width: usize,
pub height: usize,
pub cfa_pattern: [u8; 4],
pub transform: Transform,
pub maximum: u16,
pub black: SubtractBlack,
pub camera_model: Option<CameraModel>,
pub camera_white_balance: Option<[f64; 4]>,
pub white_balance: Option<[f64; 4]>,
pub camera_to_rgb: Option<[[f64; 3]; 3]>,
}
pub struct Image<T> {
pub data: Vec<T>,
pub width: usize,
pub height: usize,
/// We can assume this will be 3 for all non-obscure, modern cameras.
/// See <https://github.com/GraphiteEditor/Graphite/pull/1923#discussion_r1725070342> for more information.
pub channels: u8,
pub transform: Transform,
}
#[allow(dead_code)]
#[derive(Tag)]
struct ArwIfd {
image_width: ImageWidth,
image_height: ImageLength,
compression: Compression,
strip_byte_counts: StripByteCounts,
}
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)?;
let camera_model = metadata::identify::identify_camera_model(&ifd, &mut file).unwrap();
let transform = ifd.get_value::<Orientation, _>(&mut file)?;
let mut raw_image = if camera_model.model == "DSLR-A100" {
decoder::arw1::decode_a100(ifd, &mut file)
} else {
let sub_ifd = ifd.get_value::<SubIfd, _>(&mut file)?;
let arw_ifd = sub_ifd.get_value::<ArwIfd, _>(&mut file)?;
if arw_ifd.compression == 1 {
decoder::uncompressed::decode(sub_ifd, &mut file)
} else if arw_ifd.strip_byte_counts[0] == arw_ifd.image_width * arw_ifd.image_height {
decoder::arw2::decode(sub_ifd, &mut file)
} else {
// TODO: implement for arw 1.
todo!()
}
};
raw_image.camera_model = Some(camera_model);
raw_image.transform = transform;
raw_image.calculate_conversion_matrices();
Ok(raw_image)
}
pub fn process_8bit(raw_image: RawImage) -> Image<u8> {
let image = process_16bit(raw_image);
Image {
channels: image.channels,
data: image.data.iter().map(|x| (x >> 8) as u8).collect(),
width: image.width,
height: image.height,
transform: image.transform,
}
}
pub fn process_16bit(raw_image: RawImage) -> Image<u16> {
let subtract_black = raw_image.subtract_black_fn();
let scale_white_balance = raw_image.scale_white_balance_fn();
let scale_to_16bit = raw_image.scale_to_16bit_fn();
let raw_image = raw_image.apply((subtract_black, scale_white_balance, scale_to_16bit));
let convert_to_rgb = raw_image.convert_to_rgb_fn();
let mut record_histogram = raw_image.record_histogram_fn();
let image = raw_image.demosaic_and_apply((convert_to_rgb, &mut record_histogram));
let gamma_correction = image.gamma_correction_fn(&record_histogram.histogram);
if image.transform == Transform::Horizontal {
image.apply(gamma_correction)
} else {
image.transform_and_apply(gamma_correction)
}
}
impl RawImage {
pub fn apply(mut self, mut transform: impl RawPixelTransform) -> RawImage {
for (index, value) in self.data.iter_mut().enumerate() {
let pixel = RawPixel {
value: *value,
row: index / self.width,
column: index % self.width,
};
*value = transform.apply(pixel);
}
self
}
pub fn demosaic_and_apply(self, mut transform: impl PixelTransform) -> Image<u16> {
let mut image = vec![0; self.width * self.height * 3];
for Pixel { values, row, column } in self.linear_demosaic_iter().map(|mut pixel| {
pixel.values = transform.apply(pixel);
pixel
}) {
let pixel_index = row * self.width + column;
image[3 * pixel_index..3 * (pixel_index + 1)].copy_from_slice(&values);
}
Image {
channels: 3,
data: image,
width: self.width,
height: self.height,
transform: self.transform,
}
}
}
impl Image<u16> {
pub fn apply(mut self, mut transform: impl PixelTransform) -> Image<u16> {
for (index, values) in self.data.chunks_exact_mut(3).enumerate() {
let pixel = Pixel {
values: values.try_into().unwrap(),
row: index / self.width,
column: index % self.width,
};
values.copy_from_slice(&transform.apply(pixel));
}
self
}
pub fn transform_and_apply(self, mut transform: impl PixelTransform) -> Image<u16> {
let mut image = vec![0; self.width * self.height * 3];
let (width, height, iter) = self.transform_iter();
for Pixel { values, row, column } in iter.map(|mut pixel| {
pixel.values = transform.apply(pixel);
pixel
}) {
let pixel_index = row * width + column;
image[3 * pixel_index..3 * (pixel_index + 1)].copy_from_slice(&values);
}
Image {
channels: 3,
data: image,
width,
height,
transform: Transform::Horizontal,
}
}
}
#[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

@ -1,17 +0,0 @@
[package]
name = "tag-derive"
version = "0.0.1"
publish = false
edition = "2021"
authors = ["Graphite Authors <contact@graphite.rs>"]
description = "Derive macro for the Tag trait in raw-rs"
license = "MIT OR Apache-2.0"
repository = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/raw-rs/tag-derive"
[lib]
proc-macro = true
[dependencies]
# Workspace dependencies
quote = { workspace = true }
syn = { workspace = true }

View file

@ -138,16 +138,6 @@ version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b81e1519b0d82120d2fd469d5bfb2919a9361c48b02d82d04befc1cdd2002452"
[[package]]
name = "build-camera-data"
version = "0.0.1"
dependencies = [
"proc-macro2",
"quote",
"syn",
"toml",
]
[[package]]
name = "built"
version = "0.7.4"
@ -632,9 +622,9 @@ dependencies = [
[[package]]
name = "image"
version = "0.25.3"
version = "0.25.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d97eb9a8e0cd5b76afea91d7eecd5cf8338cd44ced04256cf1f800474b227c52"
checksum = "bc144d44a31d753b02ce64093d532f55ff8dc4ebf2ffb8a63c0dda691385acae"
dependencies = [
"bytemuck",
"byteorder-lite",
@ -1098,9 +1088,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.88"
version = "1.0.89"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c3a7fc5db1e57d5a779a352c8cdb57b29aa4c40cc69c3a68a7fedc815fbf2f9"
checksum = "f139b0662de085916d1fb67d2b4169d1addddda1919e696f3252b740b629986e"
dependencies = [
"unicode-ident",
]
@ -1228,20 +1218,29 @@ dependencies = [
]
[[package]]
name = "raw-rs"
version = "0.0.1"
name = "rawkit"
version = "0.1.0"
dependencies = [
"bitstream-io",
"build-camera-data",
"image",
"libraw-rs",
"num_enum",
"rawkit-proc-macros",
"rayon",
"reqwest",
"tag-derive",
"thiserror",
]
[[package]]
name = "rawkit-proc-macros"
version = "0.1.0"
dependencies = [
"proc-macro2",
"quote",
"syn",
"toml",
]
[[package]]
name = "rayon"
version = "1.10.0"
@ -1264,9 +1263,9 @@ dependencies = [
[[package]]
name = "reqwest"
version = "0.12.8"
version = "0.12.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f713147fbe92361e52392c73b8c9e48c04c6625bce969ef54dc901e58e042a7b"
checksum = "a77c62af46e79de0a562e1a9849205ffcb7fc1238876e9bd743357570e04046f"
dependencies = [
"base64",
"bytes",
@ -1545,9 +1544,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.79"
version = "2.0.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89132cd0bf050864e1d38dc3bbc07a0eb8e7530af26344d3d2bbbef83499f590"
checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d"
dependencies = [
"proc-macro2",
"quote",
@ -1597,14 +1596,6 @@ dependencies = [
"version-compare",
]
[[package]]
name = "tag-derive"
version = "0.0.1"
dependencies = [
"quote",
"syn",
]
[[package]]
name = "target-lexicon"
version = "0.12.16"
@ -1626,18 +1617,18 @@ dependencies = [
[[package]]
name = "thiserror"
version = "1.0.64"
version = "1.0.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84"
checksum = "5d171f59dbaa811dbbb1aee1e73db92ec2b122911a48e1390dfe327a821ddede"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.64"
version = "1.0.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3"
checksum = "b08be0f17bd307950653ce45db00cd31200d82b624b36e181337d9c7d92765b5"
dependencies = [
"proc-macro2",
"quote",

View file

@ -1,14 +1,14 @@
[workspace]
members = ["tag-derive", "build-camera-data"]
members = ["rawkit-proc-macros"]
resolver = "2"
[workspace.dependencies]
quote = "1.0.37"
syn = "2.0.79"
syn = "2.0.87"
[package]
name = "raw-rs"
version = "0.0.1"
name = "rawkit"
version = "0.1.0"
edition = "2021"
authors = ["Graphite Authors <contact@graphite.rs>"]
description = "A library to extract images from camera raw files"
@ -16,25 +16,24 @@ 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"
homepage = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/rawkit"
repository = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/rawkit"
documentation = "https://docs.rs/rawkit"
[features]
raw-rs-tests = ["dep:image", "dep:libraw-rs", "dep:reqwest", "dep:rayon"]
rawkit-tests = ["dep:image", "dep:libraw-rs", "dep:reqwest", "dep:rayon"]
[dependencies]
# Local dependencies
tag-derive = { path = "tag-derive" }
build-camera-data = { path = "build-camera-data" }
rawkit-proc-macros = { version = "0.1.0", path = "rawkit-proc-macros" }
# Required dependencies
bitstream-io = "2.5.3"
num_enum = "0.7.3"
thiserror = "1.0.64"
thiserror = "1.0.66"
# Optional dependencies (should be dev dependencies, but Cargo currently doesn't allow optional dev dependencies)
image = { version = "0.25.3", optional = true }
reqwest = { version = "0.12.8", optional = true, features = ["blocking"] }
image = { version = "0.25.4", optional = true }
reqwest = { version = "0.12.9", optional = true, features = ["blocking"] }
libraw-rs = { version = "0.0.4", optional = true }
rayon = { version = "1.10.0", optional = true }

View file

@ -0,0 +1,40 @@
[crates.io](https://crates.io/crates/rawkit) • [docs.rs](https://docs.rs/rawkit) • [repo](https://github.com/GraphiteEditor/Graphite/tree/master/libraries/rawkit)
# Rawkit 🚀
A library to extract images from camera raw files.
It currently only works with the `.arw` files from Sony's cameras. In the future, the library will add support for all other major camera manufacturers.
Rawkit 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 cameras, features, code cleanup, ergonomic enhancements, performance improvements, and documentation clarifications.
### Using Rawkit
```rust
use rawkit::RawImage;
use rawkit::tiff::values::Transform;
// Open a file for reading
let file = BufReader::new(File::open("example.arw")?);
// Decode the file to extract the raw pixels and its associated metadata
let mut raw_image = RawImage::decode(file);
// All the raw pixel data and metadata is stored within `raw_image`
println!("Initial Bayer pixel values: {:?}", raw_image.data[:10]);
println!("Image size: {} x {}", raw_image.width, raw_image.height);
println!("CFA Pattern: {:?}", raw_image.cfa_pattern);
println!("Camera Model: {:?}", raw_image.camera_model);
println!("White balance: {:?}", raw_image.white_balance);
// The metadata could also be edited if the extracted metadata needs to be customized
raw_image.white_balance = Some([2609, 1024, 1024, 1220]); // For RGGB camera
raw_image.transform = Transform::Rotate90;
// Process the raw image into an RGB image
let image = raw_image.process_8bit();
// The final image data will be stored within `image`
println!("Initial RGB pixel values: {:?}", image.data[:10]);
println!("Image size: {} x {}", image.width, image.height);
```

View file

@ -0,0 +1,23 @@
[package]
name = "rawkit-proc-macros"
version = "0.1.0"
edition = "2021"
authors = ["Graphite Authors <contact@graphite.rs>"]
description = "Procedural macros for Rawkit"
license = "MIT OR Apache-2.0"
readme = "README.md"
homepage = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/rawkit/rawkit-proc-macros"
repository = "https://github.com/GraphiteEditor/Graphite/tree/master/libraries/rawkit/rawkit-proc-macros"
documentation = "https://docs.rs/rawkit-proc-macros"
[lib]
proc-macro = true
[dependencies]
# Workspace dependencies
quote = { workspace = true }
syn = { workspace = true }
# Required dependencies
toml = "0.8.19"
proc-macro2 = "1.0.89"

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,13 @@
# Rawkit-proc-macros
Procedural macros for Rawkit.
This library is intended to be used by Rawkit. You should not be depending on this crate directly.
### Tag
A derive macro that helps to specify which metadata needs to be extracted from IFD.
### build_camera_data
A procedural macro that reads the data of all cameras from the toml files and returns the bundled data. Helps to include camera data as part of binary.

View file

@ -1,5 +1,3 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use toml::{Table, Value};
@ -46,8 +44,7 @@ impl From<Value> for CustomValue {
}
}
#[proc_macro]
pub fn build_camera_data(_: TokenStream) -> TokenStream {
pub fn build_camera_data() -> TokenStream {
let mut camera_data: Vec<(String, Table)> = Vec::new();
let mut path = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).to_path_buf();

View file

@ -0,0 +1,16 @@
extern crate proc_macro;
mod build_camera_data;
mod tag_derive;
use proc_macro::TokenStream;
#[proc_macro_derive(Tag)]
pub fn tag_derive(input: TokenStream) -> TokenStream {
tag_derive::tag_derive(input)
}
#[proc_macro]
pub fn build_camera_data(_: TokenStream) -> TokenStream {
build_camera_data::build_camera_data()
}

View file

@ -1,10 +1,7 @@
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{Data, DeriveInput, Fields};
#[proc_macro_derive(Tag)]
pub fn tag_derive(input: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse(input).unwrap();

View file

@ -4,8 +4,8 @@ use crate::tiff::values::CurveLookupTable;
use crate::tiff::{Ifd, TiffError};
use crate::{RawImage, SubtractBlack, Transform};
use rawkit_proc_macros::Tag;
use std::io::{Read, Seek};
use tag_derive::Tag;
#[allow(dead_code)]
#[derive(Tag)]

View file

@ -3,8 +3,8 @@ use crate::tiff::tags::{BitsPerSample, BlackLevel, CfaPattern, CfaPatternDim, Co
use crate::tiff::{Ifd, TiffError};
use crate::{RawImage, SubtractBlack, Transform};
use rawkit_proc_macros::Tag;
use std::io::{Read, Seek};
use tag_derive::Tag;
#[allow(dead_code)]
#[derive(Tag)]

264
libraries/rawkit/src/lib.rs Normal file
View file

@ -0,0 +1,264 @@
pub mod decoder;
pub mod demosaicing;
pub mod metadata;
pub mod postprocessing;
pub mod preprocessing;
pub mod processing;
pub mod tiff;
use crate::metadata::identify::CameraModel;
use processing::{Pixel, PixelTransform, RawPixel, RawPixelTransform};
use rawkit_proc_macros::Tag;
use tiff::file::TiffRead;
use tiff::tags::{Compression, ImageLength, ImageWidth, Orientation, StripByteCounts, SubIfd, Tag};
use tiff::values::Transform;
use tiff::{Ifd, TiffError};
use std::io::{Read, Seek};
use thiserror::Error;
pub(crate) const CHANNELS_IN_RGB: usize = 3;
pub(crate) type Histogram = [[usize; 0x2000]; CHANNELS_IN_RGB];
/// The amount of black level to be subtracted from Raw Image.
pub enum SubtractBlack {
/// Don't subtract any value.
None,
/// Subtract a singular value for all pixels in Bayer CFA Grid.
Value(u16),
/// Subtract the appropriate value for pixels in Bayer CFA Grid.
CfaGrid([u16; 4]),
}
/// Represents a Raw Image along with its metadata.
pub struct RawImage {
/// Raw pixel data stored in linear fashion.
pub data: Vec<u16>,
/// Width of the raw image.
pub width: usize,
/// Height of the raw image.
pub height: usize,
/// Bayer CFA pattern used to arrange pixels in [`RawImage::data`].
///
/// It encodes Red, Blue and Green as 0, 1, and 2 respectively.
pub cfa_pattern: [u8; 4],
/// Transformation to be applied to negate the orientation of camera.
pub transform: Transform,
/// The maximum possible value of pixel that the camera sensor could give.
pub maximum: u16,
/// The minimum possible value of pixel that the camera sensor could give.
///
/// Used to subtract the black level from the raw image.
pub black: SubtractBlack,
/// Information regarding the company and model of the camera.
pub camera_model: Option<CameraModel>,
/// White balance specified in the metadata of the raw file.
///
/// It represents the 4 values of CFA Grid which follows the same pattern as [`RawImage::cfa_pattern`].
pub camera_white_balance: Option<[f64; 4]>,
/// White balance of the raw image.
///
/// It is the same as [`RawImage::camera_white_balance`] if the raw file contains the metadata.
/// Otherwise it falls back to calculating the white balance from the color space conversion matrix.
///
/// It represents the 4 values of CFA Grid which follows the same pattern as [`RawImage::cfa_pattern`].
pub white_balance: Option<[f64; 4]>,
/// Color space conversion matrix to convert from camera's color space to sRGB.
pub camera_to_rgb: Option<[[f64; 3]; 3]>,
}
/// Represents the final RGB Image.
pub struct Image<T> {
/// Pixel data stored in a linear fashion.
pub data: Vec<T>,
/// Width of the image.
pub width: usize,
/// Height of the image.
pub height: usize,
/// The number of color channels in the image.
///
/// We can assume this will be 3 for all non-obscure, modern cameras.
/// See <https://github.com/GraphiteEditor/Graphite/pull/1923#discussion_r1725070342> for more information.
pub channels: u8,
/// The transformation required to orient the image correctly.
///
/// This will be [`Transform::Horizontal`] after the transform step is applied.
pub transform: Transform,
}
#[allow(dead_code)]
#[derive(Tag)]
struct ArwIfd {
image_width: ImageWidth,
image_height: ImageLength,
compression: Compression,
strip_byte_counts: StripByteCounts,
}
impl RawImage {
/// Create a [`RawImage`] from an input stream.
///
/// Decodes the contents of `reader` and extracts raw pixel data and metadata.
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)?;
let camera_model = metadata::identify::identify_camera_model(&ifd, &mut file).unwrap();
let transform = ifd.get_value::<Orientation, _>(&mut file)?;
let mut raw_image = if camera_model.model == "DSLR-A100" {
decoder::arw1::decode_a100(ifd, &mut file)
} else {
let sub_ifd = ifd.get_value::<SubIfd, _>(&mut file)?;
let arw_ifd = sub_ifd.get_value::<ArwIfd, _>(&mut file)?;
if arw_ifd.compression == 1 {
decoder::uncompressed::decode(sub_ifd, &mut file)
} else if arw_ifd.strip_byte_counts[0] == arw_ifd.image_width * arw_ifd.image_height {
decoder::arw2::decode(sub_ifd, &mut file)
} else {
// TODO: implement for arw 1.
todo!()
}
};
raw_image.camera_model = Some(camera_model);
raw_image.transform = transform;
raw_image.calculate_conversion_matrices();
Ok(raw_image)
}
/// Converts the [`RawImage`] to an [`Image`] with 8 bit resolution for each channel.
///
/// Applies all the processing steps to finally get RGB pixel data.
pub fn process_8bit(self) -> Image<u8> {
let image = self.process_16bit();
Image {
channels: image.channels,
data: image.data.iter().map(|x| (x >> 8) as u8).collect(),
width: image.width,
height: image.height,
transform: image.transform,
}
}
/// Converts the [`RawImage`] to an [`Image`] with 16 bit resolution for each channel.
///
/// Applies all the processing steps to finally get RGB pixel data.
pub fn process_16bit(self) -> Image<u16> {
let subtract_black = self.subtract_black_fn();
let scale_white_balance = self.scale_white_balance_fn();
let scale_to_16bit = self.scale_to_16bit_fn();
let raw_image = self.apply((subtract_black, scale_white_balance, scale_to_16bit));
let convert_to_rgb = raw_image.convert_to_rgb_fn();
let mut record_histogram = raw_image.record_histogram_fn();
let image = raw_image.demosaic_and_apply((convert_to_rgb, &mut record_histogram));
let gamma_correction = image.gamma_correction_fn(&record_histogram.histogram);
if image.transform == Transform::Horizontal {
image.apply(gamma_correction)
} else {
image.transform_and_apply(gamma_correction)
}
}
}
impl RawImage {
pub fn apply(mut self, mut transform: impl RawPixelTransform) -> RawImage {
for (index, value) in self.data.iter_mut().enumerate() {
let pixel = RawPixel {
value: *value,
row: index / self.width,
column: index % self.width,
};
*value = transform.apply(pixel);
}
self
}
pub fn demosaic_and_apply(self, mut transform: impl PixelTransform) -> Image<u16> {
let mut image = vec![0; self.width * self.height * 3];
for Pixel { values, row, column } in self.linear_demosaic_iter().map(|mut pixel| {
pixel.values = transform.apply(pixel);
pixel
}) {
let pixel_index = row * self.width + column;
image[3 * pixel_index..3 * (pixel_index + 1)].copy_from_slice(&values);
}
Image {
channels: 3,
data: image,
width: self.width,
height: self.height,
transform: self.transform,
}
}
}
impl Image<u16> {
pub fn apply(mut self, mut transform: impl PixelTransform) -> Image<u16> {
for (index, values) in self.data.chunks_exact_mut(3).enumerate() {
let pixel = Pixel {
values: values.try_into().unwrap(),
row: index / self.width,
column: index % self.width,
};
values.copy_from_slice(&transform.apply(pixel));
}
self
}
pub fn transform_and_apply(self, mut transform: impl PixelTransform) -> Image<u16> {
let mut image = vec![0; self.width * self.height * 3];
let (width, height, iter) = self.transform_iter();
for Pixel { values, row, column } in iter.map(|mut pixel| {
pixel.values = transform.apply(pixel);
pixel
}) {
let pixel_index = row * width + column;
image[3 * pixel_index..3 * (pixel_index + 1)].copy_from_slice(&values);
}
Image {
channels: 3,
data: image,
width,
height,
transform: Transform::Horizontal,
}
}
}
#[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

@ -1,5 +1,5 @@
use crate::RawImage;
use build_camera_data::build_camera_data;
use rawkit_proc_macros::build_camera_data;
pub struct CameraData {
pub black: u16,

View file

@ -2,8 +2,8 @@ use crate::tiff::file::TiffRead;
use crate::tiff::tags::{Make, Model, Tag};
use crate::tiff::{Ifd, TiffError};
use rawkit_proc_macros::Tag;
use std::io::{Read, Seek};
use tag_derive::Tag;
const COMPANY_NAMES: [&str; 22] = [
"AgfaPhoto",

View file

@ -25,18 +25,18 @@ impl<T: Fn(RawPixel) -> u16> RawPixelTransform for T {
}
macro_rules! impl_raw_pixel_transform {
($($idx:tt $t:tt),+) => {
impl<$($t,)+> RawPixelTransform for ($($t,)+)
where
$($t: RawPixelTransform,)+
{
fn apply(&mut self, mut pixel: RawPixel) -> u16 {
$(pixel.value = self.$idx.apply(pixel);)*
($($idx:tt $t:tt),+) => {
impl<$($t,)+> RawPixelTransform for ($($t,)+)
where
$($t: RawPixelTransform,)+
{
fn apply(&mut self, mut pixel: RawPixel) -> u16 {
$(pixel.value = self.$idx.apply(pixel);)*
pixel.value
}
}
};
}
}
};
}
impl_raw_pixel_transform!(0 A);
@ -59,18 +59,18 @@ impl<T: Fn(Pixel) -> [u16; CHANNELS_IN_RGB]> PixelTransform for T {
}
macro_rules! impl_pixel_transform {
($($idx:tt $t:tt),+) => {
impl<$($t,)+> PixelTransform for ($($t,)+)
where
$($t: PixelTransform,)+
{
fn apply(&mut self, mut pixel: Pixel) -> [u16; CHANNELS_IN_RGB] {
($($idx:tt $t:tt),+) => {
impl<$($t,)+> PixelTransform for ($($t,)+)
where
$($t: PixelTransform,)+
{
fn apply(&mut self, mut pixel: Pixel) -> [u16; CHANNELS_IN_RGB] {
$(pixel.values = self.$idx.apply(pixel);)*
pixel.values
}
}
};
}
}
};
}
impl_pixel_transform!(0 A);

View file

@ -1,7 +1,7 @@
// Only compile this file if the feature "raw-rs-tests" is enabled
#![cfg(feature = "raw-rs-tests")]
// Only compile this file if the feature "rawkit-tests" is enabled
#![cfg(feature = "rawkit-tests")]
use raw_rs::RawImage;
use rawkit::RawImage;
use image::codecs::png::{CompressionType, FilterType, PngEncoder};
use image::{ColorType, ImageEncoder};
@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
const TEST_FILES: [&str; 3] = ["ILCE-7M3-ARW2.3.5-blossoms.arw", "ILCE-7RM4-ARW2.3.5-kestrel.arw", "ILCE-6000-ARW2.3.1-windsock.arw"];
const BASE_URL: &str = "https://static.graphite.rs/test-data/libraries/raw-rs/";
const BASE_URL: &str = "https://static.graphite.rs/test-data/libraries/rawkit/";
const BASE_PATH: &str = "./tests/images/";
#[test]
@ -29,7 +29,7 @@ fn test_images_match_with_libraw() {
.filter(|path| path.is_file() && path.file_name().map(|file_name| file_name != ".gitkeep").unwrap_or(false))
.collect();
let failed_tests = if std::env::var("RAW_RS_TEST_RUN_SEQUENTIALLY").is_ok() {
let failed_tests = if std::env::var("RAWKIT_TEST_RUN_SEQUENTIALLY").is_ok() {
let mut failed_tests = 0;
paths.iter().for_each(|path| {
@ -80,8 +80,8 @@ fn test_image(path: &Path) -> bool {
println!("{} => Passed", path.display());
// TODO: Remove this later
let mut image = raw_rs::process_8bit(raw_image);
store_image(path, "raw_rs", &mut image.data, image.width, image.height);
let mut image = raw_image.process_8bit();
store_image(path, "rawkit", &mut image.data, image.width, image.height);
let processor = Processor::new();
let libraw_image = processor.process_8bit(&content).unwrap();
@ -134,7 +134,7 @@ fn test_raw_data(content: &[u8]) -> Result<RawImage, String> {
let libraw_raw_image = processor.decode(content).unwrap();
let mut content = Cursor::new(content);
let raw_image = raw_rs::decode(&mut content).unwrap();
let raw_image = RawImage::decode(&mut content).unwrap();
if libraw_raw_image.sizes().raw_height as usize != raw_image.height {
return Err(format!(
@ -165,7 +165,7 @@ fn test_raw_data(content: &[u8]) -> Result<RawImage, String> {
write!(&mut err_msg, "The raw data does not match").unwrap();
if std::env::var("RAW_RS_TEST_PRINT_HISTOGRAM").is_ok() {
if std::env::var("RAWKIT_TEST_PRINT_HISTOGRAM").is_ok() {
writeln!(err_msg).unwrap();
let mut histogram: HashMap<i32, usize> = HashMap::new();
@ -206,7 +206,7 @@ fn _test_final_image(content: &[u8], raw_image: RawImage) -> Result<(), String>
let processor = libraw::Processor::new();
let libraw_image = processor.process_8bit(content).unwrap();
let image = raw_rs::process_8bit(raw_image);
let image = raw_image.process_8bit();
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()));
@ -225,7 +225,7 @@ fn _test_final_image(content: &[u8], raw_image: RawImage) -> Result<(), String>
write!(&mut err_msg, "The final image does not match").unwrap();
if std::env::var("RAW_RS_TEST_PRINT_HISTOGRAM").is_ok() {
if std::env::var("RAWKIT_TEST_PRINT_HISTOGRAM").is_ok() {
writeln!(err_msg).unwrap();
let mut histogram_red: HashMap<i16, usize> = HashMap::new();
@ -338,10 +338,10 @@ fn extract_data_from_dng_images() {
}
fn extract_data_from_dng_image(path: &Path) {
use raw_rs::tiff::file::TiffRead;
use raw_rs::tiff::tags::{ColorMatrix2, Make, Model};
use raw_rs::tiff::values::ToFloat;
use raw_rs::tiff::Ifd;
use rawkit::tiff::file::TiffRead;
use rawkit::tiff::tags::{ColorMatrix2, Make, Model};
use rawkit::tiff::values::ToFloat;
use rawkit::tiff::Ifd;
use std::io::{BufReader, Write};
let reader = BufReader::new(File::open(path).unwrap());

View file

@ -66,7 +66,7 @@ in
libsoup
webkitgtk
# For Raw-rs tests
# For Rawkit tests
libraw
# Use Mold as a linker