1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
use nom::{
branch::alt, bytes::complete::tag, combinator, number::Endianness, sequence, IResult, Needed,
};
use crate::{EntryValue, ExifIter, ExifTag, GPSInfo, ParsedExifEntry};
use super::ifd::ParsedImageFileDirectory;
/// Represents parsed Exif information, can be converted from an [`ExifIter`]
/// like this: `let exif: Exif = iter.into()`.
#[derive(Clone, Debug, PartialEq)]
pub struct Exif {
ifds: Vec<ParsedImageFileDirectory>,
gps_info: Option<GPSInfo>,
}
impl Exif {
fn new(gps_info: Option<GPSInfo>) -> Exif {
Exif {
ifds: Vec::new(),
gps_info,
}
}
/// Get entry value for the specified `tag` in ifd0 (the main image).
///
/// *Note*:
///
/// - The parsing error related to this tag won't be reported by this
/// method. Either this entry is not parsed successfully, or the tag does
/// not exist in the input data, this method will return None.
///
/// - If you want to handle parsing error, please consider to use
/// [`ExifIter`].
///
/// - If you have any custom defined tag which does not exist in
/// [`ExifTag`], you can always get the entry value by a raw tag code,
/// see [`Self::get_by_tag_code`].
///
/// ## Example
///
/// ```rust
/// use nom_exif::*;
///
/// fn main() -> Result<()> {
/// let mut parser = MediaParser::new();
///
/// let ms = MediaSource::file_path("./testdata/exif.jpg")?;
/// let iter: ExifIter = parser.parse(ms)?;
/// let exif: Exif = iter.into();
///
/// assert_eq!(exif.get(ExifTag::Model).unwrap(), &"vivo X90 Pro+".into());
/// Ok(())
/// }
pub fn get(&self, tag: ExifTag) -> Option<&EntryValue> {
self.get_by_ifd_tag_code(0, tag.code())
}
/// Get entry value for the specified `tag` in the specified `ifd`.
///
/// `ifd` value range:
/// - 0: ifd0 (the main image)
/// - 1: ifd1 (thumbnail image)
///
/// *Note*:
///
/// - The parsing error related to this tag won't be reported by this
/// method. Either this entry is not parsed successfully, or the tag does
/// not exist in the input data, this method will return None.
///
/// - If you want to handle parsing error, please consider to use
/// [`ExifIter`].
///
/// ## Example
///
/// ```rust
/// use nom_exif::*;
///
/// fn main() -> Result<()> {
/// let mut parser = MediaParser::new();
///
/// let ms = MediaSource::file_path("./testdata/exif.jpg")?;
/// let iter: ExifIter = parser.parse(ms)?;
/// let exif: Exif = iter.into();
///
/// assert_eq!(exif.get_by_ifd_tag_code(0, 0x0110).unwrap(), &"vivo X90 Pro+".into());
/// assert_eq!(exif.get_by_ifd_tag_code(1, 0xa002).unwrap(), &240_u32.into());
/// Ok(())
/// }
/// ```
pub fn get_by_ifd_tag_code(&self, ifd: usize, tag: u16) -> Option<&EntryValue> {
self.ifds.get(ifd).and_then(|ifd| ifd.get(tag))
}
/// Get entry values for the specified `tags` in ifd0 (the main image).
///
/// Please note that this method will ignore errors encountered during the
/// search and parsing process, such as missing tags or errors in parsing
/// values, and handle them silently.
#[deprecated(
since = "1.5.0",
note = "please use [`Self::get`] or [`ExifIter`] instead"
)]
pub fn get_values<'b>(&self, tags: &'b [ExifTag]) -> Vec<(&'b ExifTag, EntryValue)> {
tags.iter()
.zip(tags.iter())
.filter_map(|x| {
#[allow(deprecated)]
self.get_value(x.0)
.map(|v| v.map(|v| (x.0, v)))
.unwrap_or(None)
})
.collect::<Vec<_>>()
}
/// Get entry value for the specified `tag` in ifd0 (the main image).
#[deprecated(since = "1.5.0", note = "please use [`Self::get`] instead")]
pub fn get_value(&self, tag: &ExifTag) -> crate::Result<Option<EntryValue>> {
#[allow(deprecated)]
self.get_value_by_tag_code(tag.code())
}
/// Get entry value for the specified `tag` in ifd0 (the main image).
#[deprecated(since = "1.5.0", note = "please use [`Self::get_by_tag_code`] instead")]
pub fn get_value_by_tag_code(&self, tag: u16) -> crate::Result<Option<EntryValue>> {
Ok(self.get_by_ifd_tag_code(0, tag).map(|x| x.to_owned()))
}
/// Get parsed GPS information.
pub fn get_gps_info(&self) -> crate::Result<Option<GPSInfo>> {
Ok(self.gps_info.clone())
}
fn put(&mut self, res: &mut ParsedExifEntry) {
while self.ifds.len() < res.ifd_index() + 1 {
self.ifds.push(ParsedImageFileDirectory::new());
}
if let Some(v) = res.take_value() {
self.ifds[res.ifd_index()].put(res.tag_code(), v);
}
}
}
impl From<ExifIter> for Exif {
fn from(iter: ExifIter) -> Self {
let gps_info = iter.parse_gps_info().ok().flatten();
let mut exif = Exif::new(gps_info);
for mut it in iter {
exif.put(&mut it);
}
exif
}
}
/// TIFF Header
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct TiffHeader {
pub endian: Endianness,
pub ifd0_offset: u32,
}
impl Default for TiffHeader {
fn default() -> Self {
Self {
endian: Endianness::Big,
ifd0_offset: 0,
}
}
}
pub(crate) const IFD_ENTRY_SIZE: usize = 12;
impl TiffHeader {
pub fn parse(input: &[u8]) -> IResult<&[u8], TiffHeader> {
use nom::number::streaming::{u16, u32};
let (remain, endian) = TiffHeader::parse_endian(input)?;
let (_, (_, offset)) = sequence::tuple((
combinator::verify(u16(endian), |magic| *magic == 0x2a),
u32(endian),
))(remain)?;
let header = Self {
endian,
ifd0_offset: offset,
};
Ok((remain, header))
}
pub fn parse_ifd_entry_num(input: &[u8], endian: Endianness) -> IResult<&[u8], u16> {
let (remain, num) = nom::number::streaming::u16(endian)(input)?; // Safe-slice
if num == 0 {
return Ok((remain, 0));
}
// 12 bytes per entry
let size = (num as usize)
.checked_mul(IFD_ENTRY_SIZE)
.expect("should be fit");
if size > remain.len() {
return Err(nom::Err::Incomplete(Needed::new(size - remain.len())));
}
Ok((remain, num))
}
// pub fn first_ifd<'a>(&self, input: &'a [u8], tag_ids: HashSet<u16>) -> IResult<&'a [u8], IFD> {
// // ifd0_offset starts from the beginning of Header, so we should
// // subtract the header size, which is 8
// let offset = self.ifd0_offset - 8;
// // skip to offset
// let (_, remain) = take(offset)(input)?;
// IFD::parse(remain, self.endian, tag_ids)
// }
fn parse_endian(input: &[u8]) -> IResult<&[u8], Endianness> {
combinator::map(alt((tag("MM"), tag("II"))), |endian_marker| {
if endian_marker == b"MM" {
Endianness::Big
} else {
Endianness::Little
}
})(input)
}
}
/// data.len() MUST >= 6
pub(crate) fn check_exif_header(data: &[u8]) -> bool {
use nom::bytes::complete;
assert!(data.len() >= 6);
complete::tag::<_, _, nom::error::Error<_>>(EXIF_IDENT)(data).is_ok()
}
pub(crate) fn check_exif_header2(i: &[u8]) -> IResult<&[u8], ()> {
let (remain, _) = nom::sequence::tuple((
nom::number::complete::be_u32,
nom::bytes::complete::tag(EXIF_IDENT),
))(i)?;
Ok((remain, ()))
}
pub(crate) const EXIF_IDENT: &str = "Exif\0\0";
#[cfg(test)]
mod tests {
use std::io::Read;
use std::thread;
use crate::partial_vec::PartialVec;
use test_case::test_case;
use crate::exif::input_into_iter;
use crate::jpeg::extract_exif_data;
use crate::slice::SubsliceRange;
use crate::testkit::{open_sample, read_sample};
use crate::ParsedExifEntry;
use super::*;
#[test]
fn header() {
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
let buf = [0x4d, 0x4d, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x08, 0x00];
let (_, header) = TiffHeader::parse(&buf).unwrap();
assert_eq!(
header,
TiffHeader {
endian: Endianness::Big,
ifd0_offset: 8,
}
);
}
#[test_case("exif.jpg")]
fn exif_iter_gps(path: &str) {
let buf = read_sample(path).unwrap();
let (_, data) = extract_exif_data(&buf).unwrap();
let data = data
.and_then(|x| buf.subslice_range(x))
.map(|x| PartialVec::from_vec_range(buf, x))
.unwrap();
let iter = input_into_iter(data, None).unwrap();
let gps = iter.parse_gps_info().unwrap().unwrap();
assert_eq!(gps.format_iso6709(), "+22.53113+114.02148/");
}
#[test_case("exif.jpg")]
fn clone_exif_iter_to_thread(path: &str) {
let buf = read_sample(path).unwrap();
let (_, data) = extract_exif_data(&buf).unwrap();
let data = data
.and_then(|x| buf.subslice_range(x))
.map(|x| PartialVec::from_vec_range(buf, x))
.unwrap();
let iter = input_into_iter(data, None).unwrap();
let iter2 = iter.clone();
let mut expect = String::new();
open_sample(&format!("{path}.txt"))
.unwrap()
.read_to_string(&mut expect)
.unwrap();
let jh = thread::spawn(move || iter_to_str(iter2));
let result = iter_to_str(iter);
// open_sample_w(&format!("{path}.txt"))
// .unwrap()
// .write_all(result.as_bytes())
// .unwrap();
assert_eq!(result.trim(), expect.trim());
assert_eq!(jh.join().unwrap().trim(), expect.trim());
}
fn iter_to_str(it: impl Iterator<Item = ParsedExifEntry>) -> String {
let ss = it
.map(|x| {
format!(
"ifd{}.{:<32} ยป {}",
x.ifd_index(),
x.tag()
.map(|t| t.to_string())
.unwrap_or_else(|| format!("Unknown(0x{:04x})", x.tag_code())),
x.get_result()
.map(|v| v.to_string())
.map_err(|e| e.to_string())
.unwrap_or_else(|s| s)
)
})
.collect::<Vec<String>>();
ss.join("\n")
}
}