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.

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