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
15KB

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