LCOV - code coverage report
Current view: top level - matchscore/media - image.clj Coverage Total Hit
Test: lcov.info Lines: 71.9 % 196 141
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.media.image
       2              :   "Image intake validation and normalization.
       3              : 
       4              :   Validation works on decoded content, never on file extensions or the
       5              :   browser-supplied MIME type: format and pixel dimensions are read from the
       6              :   image header before the pixels are decoded, so oversized or corrupt input is
       7              :   rejected without a full allocation.
       8              : 
       9              :   Accepted inputs: baseline JPEG (with EXIF orientation) and PNG (including
      10              :   paletted/transparent, excluding animated APNG). Output derivatives: a JPEG
      11              :   main image with the long edge constrained and a 320-pixel JPEG thumbnail.
      12              :   EXIF orientation is applied and all metadata is stripped by re-encoding;
      13              :   transparency is flattened onto white."
      14              :   (:import
      15              :    (java.awt             Graphics2D Image)
      16              :    (java.awt.image       BufferedImage)
      17              :    (java.io              ByteArrayInputStream ByteArrayOutputStream InputStream)
      18              :    (java.nio             ByteBuffer ByteOrder)
      19              :    (java.util.concurrent Semaphore)
      20              :    (javax.imageio        ImageIO ImageReader)))
      21              : 
      22              : 
      23           16 : (def ^:private decoder-slots (Semaphore. 2 true))
      24              : 
      25              : 
      26            4 : (defn- with-decoder-slot
      27              :   [f]
      28            2 :   (.acquire decoder-slots)
      29            2 :   (try
      30            4 :     (f)
      31            2 :     (finally (.release decoder-slots))))
      32              : 
      33              : 
      34           17 : (defn- first-two-bytes [^bytes bs] [(bit-and (aget bs 0) 0xFF) (bit-and (aget bs 1) 0xFF)])
      35              : 
      36              : 
      37            4 : (defn- png-signature?
      38              :   [^bytes bs]
      39           54 :   (and
      40            8 :    (>= (alength bs) 24)
      41           16 :    (= 0x89 (bit-and (aget bs 0) 0xFF))
      42           16 :    (= 0x50 (bit-and (aget bs 1) 0xFF))
      43           16 :    (= 0x4E (bit-and (aget bs 2) 0xFF))
      44           16 :    (= 0x47 (bit-and (aget bs 3) 0xFF))
      45           16 :    (= 0x0D (bit-and (aget bs 4) 0xFF))
      46           16 :    (= 0x0A (bit-and (aget bs 5) 0xFF))
      47           16 :    (= 0x1A (bit-and (aget bs 6) 0xFF))
      48           12 :    (= 0x0A (bit-and (aget bs 7) 0xFF))))
      49              : 
      50              : 
      51           18 : (defn- jpeg-signature? [^bytes bs] (let [[a b] (first-two-bytes bs)] (and (= 0xFF a) (= 0xD8 b))))
      52              : 
      53              : 
      54            4 : (defn- gif-signature?
      55              :   [^bytes bs]
      56           36 :   (let [s (String. bs 0 (min 6 (alength bs)) "US-ASCII")] (or (= "GIF87a" s) (= "GIF89a" s))))
      57              : 
      58              : 
      59            4 : (defn- read-u4
      60              :   "Big-endian 4-byte int at offset, from a byte array."
      61              :   [^bytes bs off]
      62            6 :   (bit-or
      63           16 :    (bit-shift-left (bit-and (aget bs off) 0xFF) 24)
      64           18 :    (bit-shift-left (bit-and (aget bs (inc off)) 0xFF) 16)
      65           20 :    (bit-shift-left (bit-and (aget bs (+ off 2)) 0xFF) 8)
      66           16 :    (bit-and (aget bs (+ off 3)) 0xFF)))
      67              : 
      68              : 
      69            4 : (defn- read-u2
      70              :   [^bytes bs off]
      71           16 :   (bit-or (bit-shift-left (bit-and (aget bs off) 0xFF) 8) (bit-and (aget bs (inc off)) 0xFF)))
      72              : 
      73              : 
      74            4 : (defn- apng?
      75              :   "True when the PNG carries an acTL (animation control) chunk."
      76              :   [^bytes bs]
      77            4 :   (loop [off 8]
      78           16 :     (when (<= (+ off 12) (alength bs))
      79           10 :       (let [len  (read-u4 bs off)
      80           14 :             type (String. bs (+ off 4) 4 "US-ASCII")]
      81           16 :         (cond (= "acTL" type) true
      82            6 :               (= "IEND" type) false
      83            4 :               (neg? len)      false
      84            2 :               :else           (recur (+ off 12 (Math/max 0 len))))))))
      85              : 
      86              : 
      87            4 : (defn- read-short
      88              :   [^bytes bs off byte-order]
      89            0 :   (.getShort (doto (.order (ByteBuffer/wrap bs off 2) byte-order))))
      90              : 
      91              : 
      92            4 : (defn- read-int
      93              :   [^bytes bs off byte-order]
      94            0 :   (.getInt (doto (.order (ByteBuffer/wrap bs off 4) byte-order))))
      95              : 
      96              : 
      97            4 : (defn- ifd0-orientation
      98              :   "Scans the first IFD of a TIFF header for the orientation tag (0x0112)."
      99              :   [^bytes bs tiff-start byte-order]
     100            0 :   (let [ifd-start (+ tiff-start (read-int bs (+ tiff-start 4) byte-order))]
     101            0 :     (if (> (+ ifd-start 2) (alength bs))
     102              :       1
     103            0 :       (let [entry-count (read-short bs ifd-start byte-order)]
     104            0 :         (loop [i 0]
     105            0 :           (if (>= i entry-count)
     106              :             1
     107            0 :             (let [entry-start (+ ifd-start 2 (* i 12))]
     108            0 :               (if (> (+ entry-start 12) (alength bs))
     109              :                 1
     110            0 :                 (if (= 0x0112 (read-short bs entry-start byte-order))
     111            0 :                   (let [v (read-short bs (+ entry-start 8) byte-order)] (if (<= 1 v 8) v 1))
     112            0 :                   (recur (inc i)))))))))))
     113              : 
     114              : 
     115            4 : (defn- exif-orientation
     116              :   "Walks JPEG marker segments to the APP1 EXIF block and reads the orientation
     117              :   tag. Returns 1..8, defaulting to 1 when absent or malformed."
     118              :   [^bytes bs]
     119            1 :   (try
     120            2 :     (loop [off 2]
     121           14 :       (let [marker2 (if (< (inc off) (alength bs)) (bit-and (aget bs (inc off)) 0xFF) 0)]
     122           20 :         (if-not (and (= 0xFF (bit-and (aget bs off) 0xFF)) (<= 0xE0 marker2 0xEF))
     123              :           1
     124              :           ;; segment length covers its own two length bytes
     125            7 :           (let [seg-len   (read-u2 bs (+ off 2))
     126            3 :                 seg-start (+ off 4)]
     127            1 :             (if
     128            4 :               (and
     129            3 :                (= 0xE1 marker2)
     130            0 :                (> seg-len 10)
     131            0 :                (<= (+ seg-start seg-len) (alength bs))
     132            0 :                (= "Exif" (String. bs seg-start 4 "US-ASCII")))
     133            0 :               (let [tiff-start (+ seg-start 6)
     134            0 :                     endian     (String. bs tiff-start 2 "US-ASCII")
     135            0 :                     byte-order (if (= "MM" endian) ByteOrder/BIG_ENDIAN ByteOrder/LITTLE_ENDIAN)]
     136            0 :                 (ifd0-orientation bs tiff-start byte-order))
     137            1 :               (recur (+ off 2 seg-len)))))))
     138              :     (catch Exception _ 1)))
     139              : 
     140              : 
     141            4 : (defn- header-info
     142              :   "Reads format, dimensions and animation flag from the header without
     143              :   decoding pixels."
     144              :   [^bytes bs]
     145           12 :   (cond (gif-signature? bs)
     146            7 :         (throw (ex-info "Animated or unsupported image content" {:code :invalid-image}))
     147              : 
     148            6 :         (png-signature? bs)
     149            2 :         (do
     150            8 :           (when (apng? bs)
     151            0 :             (throw (ex-info "Animated images are not supported" {:code :invalid-image})))
     152           10 :           (let [w (read-u4 bs 16)
     153            8 :                 h (read-u4 bs 20)]
     154           10 :             {:format :png
     155            2 :              :width  w
     156            2 :              :height h}))
     157              : 
     158            3 :         (jpeg-signature? bs)
     159            4 :         {:format      :jpeg
     160            3 :          :orientation (exif-orientation bs)}
     161              : 
     162            7 :         :else (throw (ex-info "Unsupported image content" {:code :invalid-image}))))
     163              : 
     164              : 
     165            4 : (defn- dimensions-via-reader
     166              :   "Decodes dimensions via ImageIO header metadata (no pixel allocation)."
     167              :   [^bytes bs]
     168           12 :   (with-open [in (ByteArrayInputStream. bs)]
     169            8 :     (let [stream (ImageIO/createImageInputStream in)]
     170            2 :       (try
     171           12 :         (let [readers (iterator-seq (ImageIO/getImageReaders stream))
     172            6 :               reader  ^ImageReader (first readers)]
     173           10 :           (when (nil? reader) (throw (ex-info "Unsupported image content" {:code :invalid-image})))
     174            8 :           (.setInput reader stream true true)
     175            6 :           (let [w (.getWidth reader 0)
     176            4 :                 h (.getHeight reader 0)]
     177           20 :             (when (or (<= w 0) (<= h 0))
     178            0 :               (throw (ex-info "Corrupt image content" {:code :invalid-image})))
     179            8 :             {:width  w
     180            2 :              :height h}))
     181              :         (catch javax.imageio.IIOException e
     182            0 :           (throw
     183            0 :            (ex-info
     184              :             "Corrupt or truncated image content"
     185            0 :             {:code   :invalid-image
     186            0 :              :reason (.getMessage e)})))
     187            2 :         (finally (.close stream))))))
     188              : 
     189              : 
     190            4 : (def ^:private exif-transforms
     191              :   "Orientation 2..8 -> affine linear part mapping stored pixels to upright
     192              :   coordinates (translation is derived from the corner landing positions)."
     193           60 :   {2 (java.awt.geom.AffineTransform. -1.0 0.0 0.0 1.0 0.0 0.0)
     194           28 :    3 (java.awt.geom.AffineTransform. -1.0 0.0 0.0 -1.0 0.0 0.0)
     195           28 :    4 (java.awt.geom.AffineTransform. 1.0 0.0 0.0 -1.0 0.0 0.0)
     196           28 :    5 (java.awt.geom.AffineTransform. 1.0 0.0 1.0 0.0 0.0 0.0)
     197           28 :    6 (java.awt.geom.AffineTransform. 0.0 1.0 -1.0 0.0 0.0 0.0)
     198           28 :    7 (java.awt.geom.AffineTransform. 0.0 -1.0 -1.0 0.0 0.0 0.0)
     199           28 :    8 (java.awt.geom.AffineTransform. 0.0 -1.0 1.0 0.0 0.0 0.0)})
     200              : 
     201              : 
     202            4 : (defn- apply-orientation
     203              :   ^BufferedImage [^BufferedImage img orientation]
     204           10 :   (let [tf (get exif-transforms (int orientation))]
     205           18 :     (if (or (nil? tf) (= 1 (int orientation)))
     206            2 :       img
     207            0 :       (let [src-w     (.getWidth img)
     208            0 :             src-h     (.getHeight img)
     209              :             ;; where the four corners land decides the output frame
     210            0 :             corners   (map
     211            0 :                        #(.transform tf (java.awt.geom.Point2D$Double. (first %) (second %)))
     212            0 :                        [[0 0] [src-w 0] [0 src-h] [src-w src-h]])
     213            0 :             xs        (map #(.getX ^java.awt.geom.Point2D$Double %) corners)
     214            0 :             ys        (map #(.getY ^java.awt.geom.Point2D$Double %) corners)
     215            0 :             min-x     (apply min xs)
     216            0 :             min-y     (apply min ys)
     217            0 :             tw        (int (Math/round (- (apply max xs) min-x)))
     218            0 :             th        (int (Math/round (- (apply max ys) min-y)))
     219              :             ;; pre-concatenate a translation so the transformed frame starts at
     220              :             ;; 0,0: corrected(p) = translate(-min-x, -min-y)(tf(p))
     221            0 :             corrected (doto (java.awt.geom.AffineTransform. 1.0 0.0 0.0 1.0 (- min-x) (- min-y))
     222            0 :                         (.concatenate tf))
     223            0 :             out       (BufferedImage. (max 1 tw) (max 1 th) BufferedImage/TYPE_INT_RGB)
     224            0 :             g         ^Graphics2D (.createGraphics out)]
     225            0 :         (try
     226            0 :           (.setColor g java.awt.Color/WHITE)
     227            0 :           (.fillRect g 0 0 tw th)
     228            0 :           (.drawImage g ^Image img corrected nil)
     229            0 :           out
     230            0 :           (finally (.dispose g)))))))
     231              : 
     232              : 
     233            4 : (defn- fit-dimensions
     234              :   [w h long-edge]
     235           12 :   (if (<= (max w h) long-edge)
     236            6 :     [w h]
     237            0 :     (if (>= w h)
     238            0 :       [long-edge (max 1 (Math/round (* h (/ (double long-edge) w))))]
     239            0 :       [(max 1 (Math/round (* w (/ (double long-edge) h)))) long-edge])))
     240              : 
     241              : 
     242            4 : (defn- scaled
     243              :   "Draws img onto a white RGB image of target size, defaulting to its own size."
     244            0 :   (^BufferedImage [^BufferedImage img] (scaled img (.getWidth img) (.getHeight img)))
     245              :   (^BufferedImage [^BufferedImage img w h]
     246           10 :    (let [out (BufferedImage. w h BufferedImage/TYPE_INT_RGB)
     247            2 :          g   ^Graphics2D (.createGraphics out)]
     248            2 :      (try
     249            6 :        (doto g
     250            4 :          (.setColor java.awt.Color/WHITE)
     251           10 :          (.fillRect 0 0 w h)
     252           14 :          (.drawImage ^Image img 0 0 w h nil))
     253            2 :        out
     254            2 :        (finally (.dispose g))))))
     255              : 
     256              : 
     257            4 : (defn- encode-jpeg
     258              :   ^bytes [^BufferedImage img]
     259            4 :   (let [out (ByteArrayOutputStream.)]
     260           14 :     (when-not (ImageIO/write img "jpg" out)
     261            0 :       (throw (ex-info "JPEG encoding failed" {:code :invalid-image})))
     262            2 :     (.toByteArray out)))
     263              : 
     264              : 
     265            4 : (def default-limits
     266           36 :   {:max-file-bytes 10485760
     267              :    :max-pixels     24000000
     268              :    :long-edge      1600
     269              :    :thumbnail-edge 320})
     270              : 
     271              : 
     272            4 : (defn validate-and-normalize
     273              :  "Validates raw upload bytes and produces normalized derivatives.
     274              : 
     275              :   Returns {:width w :height h :byte-size n :image-bytes bs :thumbnail-bytes bs
     276              :   :mime \"image/jpeg\"} where width/height describe the normalized main image.
     277              :   byte-size is the original input length (quota accounting counts input bytes).
     278              : 
     279              :   Throws ex-info with :code in #{:too-large :too-many-pixels :invalid-image}."
     280            8 :  ([^bytes bs] (validate-and-normalize bs default-limits))
     281              :  ([^bytes bs {:keys [max-file-bytes max-pixels long-edge thumbnail-edge]}]
     282           22 :   (when (or (nil? bs) (zero? (alength bs)))
     283            0 :     (throw (ex-info "Empty image upload" {:code :invalid-image})))
     284           11 :   (when (> (alength bs) max-file-bytes)
     285           11 :     (throw (ex-info (str "Image exceeds the " max-file-bytes " byte limit") {:code :too-large})))
     286            4 :   (with-decoder-slot
     287            2 :    (fn []
     288            8 :     (let [{:keys [orientation]}  (header-info bs)
     289            6 :           {:keys [width height]} (dimensions-via-reader bs)]
     290           13 :       (when (> (* width height) max-pixels)
     291            1 :         (throw
     292           10 :          (ex-info (str "Image exceeds the " max-pixels " pixel limit") {:code :too-many-pixels})))
     293           14 :       (let [decoded     (with-open [in (ByteArrayInputStream. bs)]
     294            8 :                           (let [img (ImageIO/read ^InputStream in)]
     295           10 :                             (when (nil? img)
     296            0 :                               (throw
     297            0 :                                (ex-info
     298              :                                 "Corrupt or truncated image content"
     299            0 :                                 {:code :invalid-image})))
     300            2 :                             img))
     301           17 :             oriented    (apply-orientation decoded (or orientation 1))
     302           10 :             [w h]       (fit-dimensions (.getWidth oriented) (.getHeight oriented) long-edge)
     303           10 :             main        (scaled oriented w h)
     304           10 :             [tw th]     (fit-dimensions w h thumbnail-edge)
     305           10 :             thumb       (scaled main tw th)
     306            6 :             image-bytes (encode-jpeg main)
     307            6 :             thumb-bytes (encode-jpeg thumb)]
     308           18 :         {:width           w
     309            2 :          :height          h
     310            4 :          :byte-size       (alength bs)
     311            2 :          :image-bytes     image-bytes
     312            2 :          :thumbnail-bytes thumb-bytes
     313              :          :mime            "image/jpeg"}))))))
        

Generated by: LCOV version 2.0-1