You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

468 lines
16KB

  1. use std::collections::hash_map::DefaultHasher;
  2. use std::collections::hash_map::Entry as HEntry;
  3. use std::collections::HashMap;
  4. use std::fs::{self, File};
  5. use std::hash::{Hash, Hasher};
  6. use std::path::{Path, PathBuf};
  7. use image::jpeg::JPEGEncoder;
  8. use image::png::PNGEncoder;
  9. use image::{FilterType, GenericImageView};
  10. use lazy_static::lazy_static;
  11. use rayon::prelude::*;
  12. use regex::Regex;
  13. use errors::{Error, Result};
  14. use utils::fs as ufs;
  15. static RESIZED_SUBDIR: &str = "processed_images";
  16. lazy_static! {
  17. pub static ref RESIZED_FILENAME: Regex =
  18. Regex::new(r#"([0-9a-f]{16})([0-9a-f]{2})[.](jpg|png)"#).unwrap();
  19. }
  20. /// Describes the precise kind of a resize operation
  21. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  22. pub enum ResizeOp {
  23. /// A simple scale operation that doesn't take aspect ratio into account
  24. Scale(u32, u32),
  25. /// Scales the image to a specified width with height computed such
  26. /// that aspect ratio is preserved
  27. FitWidth(u32),
  28. /// Scales the image to a specified height with width computed such
  29. /// that aspect ratio is preserved
  30. FitHeight(u32),
  31. /// If the image is larger than the specified width or height, scales the image such
  32. /// that it fits within the specified width and height preserving aspect ratio.
  33. /// Either dimension may end up being smaller, but never larger than specified.
  34. Fit(u32, u32),
  35. /// Scales the image such that it fills the specified width and height.
  36. /// Output will always have the exact dimensions specified.
  37. /// The part of the image that doesn't fit in the thumbnail due to differing
  38. /// aspect ratio will be cropped away, if any.
  39. Fill(u32, u32),
  40. }
  41. impl ResizeOp {
  42. pub fn from_args(op: &str, width: Option<u32>, height: Option<u32>) -> Result<ResizeOp> {
  43. use ResizeOp::*;
  44. // Validate args:
  45. match op {
  46. "fit_width" => {
  47. if width.is_none() {
  48. return Err("op=\"fit_width\" requires a `width` argument".to_string().into());
  49. }
  50. }
  51. "fit_height" => {
  52. if height.is_none() {
  53. return Err("op=\"fit_height\" requires a `height` argument"
  54. .to_string()
  55. .into());
  56. }
  57. }
  58. "scale" | "fit" | "fill" => {
  59. if width.is_none() || height.is_none() {
  60. return Err(
  61. format!("op={} requires a `width` and `height` argument", op).into()
  62. );
  63. }
  64. }
  65. _ => return Err(format!("Invalid image resize operation: {}", op).into()),
  66. };
  67. Ok(match op {
  68. "scale" => Scale(width.unwrap(), height.unwrap()),
  69. "fit_width" => FitWidth(width.unwrap()),
  70. "fit_height" => FitHeight(height.unwrap()),
  71. "fit" => Fit(width.unwrap(), height.unwrap()),
  72. "fill" => Fill(width.unwrap(), height.unwrap()),
  73. _ => unreachable!(),
  74. })
  75. }
  76. pub fn width(self) -> Option<u32> {
  77. use ResizeOp::*;
  78. match self {
  79. Scale(w, _) => Some(w),
  80. FitWidth(w) => Some(w),
  81. FitHeight(_) => None,
  82. Fit(w, _) => Some(w),
  83. Fill(w, _) => Some(w),
  84. }
  85. }
  86. pub fn height(self) -> Option<u32> {
  87. use ResizeOp::*;
  88. match self {
  89. Scale(_, h) => Some(h),
  90. FitWidth(_) => None,
  91. FitHeight(h) => Some(h),
  92. Fit(_, h) => Some(h),
  93. Fill(_, h) => Some(h),
  94. }
  95. }
  96. }
  97. impl From<ResizeOp> for u8 {
  98. fn from(op: ResizeOp) -> u8 {
  99. use ResizeOp::*;
  100. match op {
  101. Scale(_, _) => 1,
  102. FitWidth(_) => 2,
  103. FitHeight(_) => 3,
  104. Fit(_, _) => 4,
  105. Fill(_, _) => 5,
  106. }
  107. }
  108. }
  109. #[allow(clippy::derive_hash_xor_eq)]
  110. impl Hash for ResizeOp {
  111. fn hash<H: Hasher>(&self, hasher: &mut H) {
  112. hasher.write_u8(u8::from(*self));
  113. if let Some(w) = self.width() {
  114. hasher.write_u32(w);
  115. }
  116. if let Some(h) = self.height() {
  117. hasher.write_u32(h);
  118. }
  119. }
  120. }
  121. /// Thumbnail image format
  122. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  123. pub enum Format {
  124. /// JPEG, The `u8` argument is JPEG quality (in percent).
  125. Jpeg(u8),
  126. /// PNG
  127. Png,
  128. }
  129. impl Format {
  130. pub fn from_args(source: &str, format: &str, quality: u8) -> Result<Format> {
  131. use Format::*;
  132. assert!(quality > 0 && quality <= 100, "Jpeg quality must be within the range [1; 100]");
  133. match format {
  134. "auto" => match Self::is_lossy(source) {
  135. Some(true) => Ok(Jpeg(quality)),
  136. Some(false) => Ok(Png),
  137. None => Err(format!("Unsupported image file: {}", source).into()),
  138. },
  139. "jpeg" | "jpg" => Ok(Jpeg(quality)),
  140. "png" => Ok(Png),
  141. _ => Err(format!("Invalid image format: {}", format).into()),
  142. }
  143. }
  144. /// Looks at file's extension and, if it's a supported image format, returns whether the format is lossless
  145. pub fn is_lossy<P: AsRef<Path>>(p: P) -> Option<bool> {
  146. p.as_ref()
  147. .extension()
  148. .and_then(std::ffi::OsStr::to_str)
  149. .map(|ext| match ext.to_lowercase().as_str() {
  150. "jpg" | "jpeg" => Some(true),
  151. "png" => Some(false),
  152. "gif" => Some(false),
  153. "bmp" => Some(false),
  154. _ => None,
  155. })
  156. .unwrap_or(None)
  157. }
  158. fn extension(&self) -> &str {
  159. // Kept in sync with RESIZED_FILENAME and op_filename
  160. use Format::*;
  161. match *self {
  162. Png => "png",
  163. Jpeg(_) => "jpg",
  164. }
  165. }
  166. }
  167. #[allow(clippy::derive_hash_xor_eq)]
  168. impl Hash for Format {
  169. fn hash<H: Hasher>(&self, hasher: &mut H) {
  170. use Format::*;
  171. let q = match *self {
  172. Png => 0,
  173. Jpeg(q) => q,
  174. };
  175. hasher.write_u8(q);
  176. }
  177. }
  178. /// Holds all data needed to perform a resize operation
  179. #[derive(Debug, PartialEq, Eq)]
  180. pub struct ImageOp {
  181. source: String,
  182. op: ResizeOp,
  183. format: Format,
  184. /// Hash of the above parameters
  185. hash: u64,
  186. /// If there is a hash collision with another ImageOp, this contains a sequential ID > 1
  187. /// identifying the collision in the order as encountered (which is essentially random).
  188. /// Therefore, ImageOps with collisions (ie. collision_id > 0) are always considered out of date.
  189. /// Note that this is very unlikely to happen in practice
  190. collision_id: u32,
  191. }
  192. impl ImageOp {
  193. pub fn new(source: String, op: ResizeOp, format: Format) -> ImageOp {
  194. let mut hasher = DefaultHasher::new();
  195. hasher.write(source.as_ref());
  196. op.hash(&mut hasher);
  197. format.hash(&mut hasher);
  198. let hash = hasher.finish();
  199. ImageOp { source, op, format, hash, collision_id: 0 }
  200. }
  201. pub fn from_args(
  202. source: String,
  203. op: &str,
  204. width: Option<u32>,
  205. height: Option<u32>,
  206. format: &str,
  207. quality: u8,
  208. ) -> Result<ImageOp> {
  209. let op = ResizeOp::from_args(op, width, height)?;
  210. let format = Format::from_args(&source, format, quality)?;
  211. Ok(Self::new(source, op, format))
  212. }
  213. fn perform(&self, content_path: &Path, target_path: &Path) -> Result<()> {
  214. use ResizeOp::*;
  215. let src_path = content_path.join(&self.source);
  216. if !ufs::file_stale(&src_path, target_path) {
  217. return Ok(());
  218. }
  219. let mut img = image::open(&src_path)?;
  220. let (img_w, img_h) = img.dimensions();
  221. const RESIZE_FILTER: FilterType = FilterType::Lanczos3;
  222. const RATIO_EPSILLION: f32 = 0.1;
  223. let img = match self.op {
  224. Scale(w, h) => img.resize_exact(w, h, RESIZE_FILTER),
  225. FitWidth(w) => img.resize(w, u32::max_value(), RESIZE_FILTER),
  226. FitHeight(h) => img.resize(u32::max_value(), h, RESIZE_FILTER),
  227. Fit(w, h) => {
  228. if img_w > w || img_h > h {
  229. img.resize(w, h, RESIZE_FILTER)
  230. } else {
  231. img
  232. }
  233. }
  234. Fill(w, h) => {
  235. let factor_w = img_w as f32 / w as f32;
  236. let factor_h = img_h as f32 / h as f32;
  237. if (factor_w - factor_h).abs() <= RATIO_EPSILLION {
  238. // If the horizontal and vertical factor is very similar,
  239. // that means the aspect is similar enough that there's not much point
  240. // in cropping, so just perform a simple scale in this case.
  241. img.resize_exact(w, h, RESIZE_FILTER)
  242. } else {
  243. // We perform the fill such that a crop is performed first
  244. // and then resize_exact can be used, which should be cheaper than
  245. // resizing and then cropping (smaller number of pixels to resize).
  246. let (crop_w, crop_h) = if factor_w < factor_h {
  247. (img_w, (factor_w * h as f32).round() as u32)
  248. } else {
  249. ((factor_h * w as f32).round() as u32, img_h)
  250. };
  251. let (offset_w, offset_h) = if factor_w < factor_h {
  252. (0, (img_h - crop_h) / 2)
  253. } else {
  254. ((img_w - crop_w) / 2, 0)
  255. };
  256. img.crop(offset_w, offset_h, crop_w, crop_h).resize_exact(w, h, RESIZE_FILTER)
  257. }
  258. }
  259. };
  260. let mut f = File::create(target_path)?;
  261. let (img_w, img_h) = img.dimensions();
  262. match self.format {
  263. Format::Png => {
  264. let enc = PNGEncoder::new(&mut f);
  265. enc.encode(&img.raw_pixels(), img_w, img_h, img.color())?;
  266. }
  267. Format::Jpeg(q) => {
  268. let mut enc = JPEGEncoder::new_with_quality(&mut f, q);
  269. enc.encode(&img.raw_pixels(), img_w, img_h, img.color())?;
  270. }
  271. }
  272. Ok(())
  273. }
  274. }
  275. /// A strcture into which image operations can be enqueued and then performed.
  276. /// All output is written in a subdirectory in `static_path`,
  277. /// taking care of file stale status based on timestamps and possible hash collisions.
  278. #[derive(Debug)]
  279. pub struct Processor {
  280. content_path: PathBuf,
  281. resized_path: PathBuf,
  282. resized_url: String,
  283. /// A map of a ImageOps by their stored hash.
  284. /// Note that this cannot be a HashSet, because hashset handles collisions and we don't want that,
  285. /// we need to be aware of and handle collisions ourselves.
  286. img_ops: HashMap<u64, ImageOp>,
  287. /// Hash collisions go here:
  288. img_ops_collisions: Vec<ImageOp>,
  289. }
  290. impl Processor {
  291. pub fn new(content_path: PathBuf, static_path: &Path, base_url: &str) -> Processor {
  292. Processor {
  293. content_path,
  294. resized_path: static_path.join(RESIZED_SUBDIR),
  295. resized_url: Self::resized_url(base_url),
  296. img_ops: HashMap::new(),
  297. img_ops_collisions: Vec::new(),
  298. }
  299. }
  300. fn resized_url(base_url: &str) -> String {
  301. if base_url.ends_with('/') {
  302. format!("{}{}", base_url, RESIZED_SUBDIR)
  303. } else {
  304. format!("{}/{}", base_url, RESIZED_SUBDIR)
  305. }
  306. }
  307. pub fn set_base_url(&mut self, base_url: &str) {
  308. self.resized_url = Self::resized_url(base_url);
  309. }
  310. pub fn source_exists(&self, source: &str) -> bool {
  311. self.content_path.join(source).exists()
  312. }
  313. pub fn num_img_ops(&self) -> usize {
  314. self.img_ops.len() + self.img_ops_collisions.len()
  315. }
  316. fn insert_with_collisions(&mut self, mut img_op: ImageOp) -> u32 {
  317. match self.img_ops.entry(img_op.hash) {
  318. HEntry::Occupied(entry) => {
  319. if *entry.get() == img_op {
  320. return 0;
  321. }
  322. }
  323. HEntry::Vacant(entry) => {
  324. entry.insert(img_op);
  325. return 0;
  326. }
  327. }
  328. // If we get here, that means a hash collision.
  329. // This is detected when there is an ImageOp with the same hash in the `img_ops`
  330. // map but which is not equal to this one.
  331. // To deal with this, all collisions get a (random) sequential ID number.
  332. // First try to look up this ImageOp in `img_ops_collisions`, maybe we've
  333. // already seen the same ImageOp.
  334. // At the same time, count IDs to figure out the next free one.
  335. // Start with the ID of 2, because we'll need to use 1 for the ImageOp
  336. // already present in the map:
  337. let mut collision_id = 2;
  338. for op in self.img_ops_collisions.iter().filter(|op| op.hash == img_op.hash) {
  339. if *op == img_op {
  340. // This is a colliding ImageOp, but we've already seen an equal one
  341. // (not just by hash, but by content too), so just return its ID:
  342. return collision_id;
  343. } else {
  344. collision_id += 1;
  345. }
  346. }
  347. // If we get here, that means this is a new colliding ImageOp and
  348. // `collision_id` is the next free ID
  349. if collision_id == 2 {
  350. // This is the first collision found with this hash, update the ID
  351. // of the matching ImageOp in the map.
  352. self.img_ops.get_mut(&img_op.hash).unwrap().collision_id = 1;
  353. }
  354. img_op.collision_id = collision_id;
  355. self.img_ops_collisions.push(img_op);
  356. collision_id
  357. }
  358. fn op_filename(hash: u64, collision_id: u32, format: Format) -> String {
  359. // Please keep this in sync with RESIZED_FILENAME
  360. assert!(collision_id < 256, "Unexpectedly large number of collisions: {}", collision_id);
  361. format!("{:016x}{:02x}.{}", hash, collision_id, format.extension())
  362. }
  363. fn op_url(&self, hash: u64, collision_id: u32, format: Format) -> String {
  364. format!("{}/{}", &self.resized_url, Self::op_filename(hash, collision_id, format))
  365. }
  366. pub fn insert(&mut self, img_op: ImageOp) -> String {
  367. let hash = img_op.hash;
  368. let format = img_op.format;
  369. let collision_id = self.insert_with_collisions(img_op);
  370. self.op_url(hash, collision_id, format)
  371. }
  372. pub fn prune(&self) -> Result<()> {
  373. // Do not create folders if they don't exist
  374. if !self.resized_path.exists() {
  375. return Ok(());
  376. }
  377. ufs::ensure_directory_exists(&self.resized_path)?;
  378. let entries = fs::read_dir(&self.resized_path)?;
  379. for entry in entries {
  380. let entry_path = entry?.path();
  381. if entry_path.is_file() {
  382. let filename = entry_path.file_name().unwrap().to_string_lossy();
  383. if let Some(capts) = RESIZED_FILENAME.captures(filename.as_ref()) {
  384. let hash = u64::from_str_radix(capts.get(1).unwrap().as_str(), 16).unwrap();
  385. let collision_id =
  386. u32::from_str_radix(capts.get(2).unwrap().as_str(), 16).unwrap();
  387. if collision_id > 0 || !self.img_ops.contains_key(&hash) {
  388. fs::remove_file(&entry_path)?;
  389. }
  390. }
  391. }
  392. }
  393. Ok(())
  394. }
  395. pub fn do_process(&mut self) -> Result<()> {
  396. if !self.img_ops.is_empty() {
  397. ufs::ensure_directory_exists(&self.resized_path)?;
  398. }
  399. self.img_ops
  400. .par_iter()
  401. .map(|(hash, op)| {
  402. let target =
  403. self.resized_path.join(Self::op_filename(*hash, op.collision_id, op.format));
  404. op.perform(&self.content_path, &target)
  405. .map_err(|e| Error::chain(format!("Failed to process image: {}", op.source), e))
  406. })
  407. .collect::<Result<()>>()
  408. }
  409. }